SQl 语句 表的连接

当涉及到多个表查询时就需要使用将表连接的方法进行查询。

SQL语句连接的方式根本上分为5种:

1 •EQUI JOIN
2 •SEMI JOIN
3 •ANTI JOIN
4 •CROSS JOIN
5 •DIVISION

1.EQUI JOIN

这是最基本的JOIN(连接)操作包括:内连接,左连接,右连接,全连接

内连接:内连接使用比较运算符根据每个表共有的列的值匹配两个表中的行。

 语法格式:inner join

1 select  *
2 from  Student_One
3 inner join   Student_Two 
4 on  Student_One.sno=Student_One.sno;

左连接:左连接的结果集包括left join 子句中指定的所有的行,不仅仅连接所匹配的行,如果左表的某行在右表中没有匹配行,在相关联的结果集行中右表的所有选择列表为空值。

  语法格式:left join

1 select  *
2 from  Student_One
3 left join   Student_Two 
4 on  Student_One.sno=Student_One.sno;

 

右连接:右连接是左连接的反向连接。返回右表的所有行,如果右表某行在左表没有匹配行,则左表对应的返回空值。

  语法格式:right join

1 select *
2 from  Student_One
3 right join   Student_Two 
4 on  Student_One.sno=Student_One.sno;

全连接:返回左表和有右表中的所有行(有匹配的返回匹配的行)。当某行在另一个表中没有匹配时,另一个表的选择列表列包含空值。如果有匹配行,则整个结果集行包含基表的数据值。

  语法格式:full join

1 select *
2 from  Student_One
3 full join   Student_Two 
4 on  Student_One.sno=Student_One.sno;

交叉连接:交叉连接返回左表中的所有行,左表的每一行与右表所有行组合。交叉连接也叫笛卡儿积。

注意:交叉连接有两种,显式和隐式的,没有on子句,返回的是两表的笛卡尔积。

隐式:

1 select *
2 from  Student_One,Student_Two

显式:

1 select *
2 from Student_One
3 cross join Student_Two;

from子句中的表或者视图可通过内连接或全连接按任意顺序指定;但是用左连接或右连接指定表或视图的顺序很重要。

2.SEMI JOIN

这种连接关系在SQL中有两种表现方式:使用IN 或者 使用EXITS。

IN 比 EXITS 的可读性好

EXITS 比 IN 的表达性好(适合复杂的语句)

例子:

1 -- Using IN
2 select *
3 FROM author
4 where author.id IN (select book.author_id from book)
5  
6 -- Using EXISTS
7 select *
8 from author
9 where EXISTS (select 1 from book where book.author_id = author.id)

 

3.ANTI JOIN

这种连接的关系和SEMI JOIN 相反。在 IN 或 EXITS 前加 NOT 关键字

1 -- Using IN
2 select *
3 from author
4 where  author.id NOT IN (select book.author_id from book)
5  
6 -- Using EXISTS
7 select *
8 from  author
9 where NOT EXISTS (select 1 from book where book.author_id = author.id)

 

多表连接时SQl的常用技术 必须掌握!

posted @ 2016-12-15 12:45  436酱油哥  阅读(3848)  评论(0编辑  收藏  举报