优选主流主机商
任何主机均需规范使用

SQL多表Join实战案例详解:从入门到精通,掌握数据库高效查询技巧

最常见的 join 类型:sql inner join(简单的 join)、sql left join、sql right join、sql full join,其中前一种是内连接,后三种是外链接。

假设我们有两张表,table a是上边的表,table b是下边的表。

table a

id name
1 google
2 淘宝
3 微博
4 facebook

table b

id address
1 美国
5 中国
3 中国
6 美国

一、inner join

内连接是最常见的一种连接,只连接匹配的行。

inner join语法

1 2 3 4 5 select column_name(s) from table 1 inner join table 2 on table 1.column_name= table 2.column_name

注释:inner join与join是相同inner join产生的结果集中,是1和2的交集。

1 2 select * from table a inner join table b on table a.id= table b.id

执行以上sql输出结果如下:

id name address
1 google 美国
3 微博 中国

二、left join

left join返回左表的全部行和右表满足on条件的行,如果左表的行在右表中没有匹配,那么这一行右表中对应数据用null代替。

left join 语法

1 2 3 4 select column_name(s) from table 1 left join table 2 on table 1.column_name= table 2.column_name

注释:在某些数据库中,left join 称为left outer join

left join产生表1的完全集,而2表中匹配的则有值,没有匹配的则以null值取代。

1 2 select * from table a left join table b on table a.id= table b.id

执行以上sql输出结果如下:

id name address
1 google 美国
2 淘宝 null
3 微博 中国
4 facebook null

三、right join

right join返回右表的全部行和左表满足on条件的行,如果右表的行在左表中没有匹配,那么这一行左表中对应数据用null代替。

right join语法

1 2 3 4 select column_name(s) from table 1 right join table 2 on table 1.column_name= table 2.column_name

注释:在某些数据库中,right join 称为right outer joinright join产生表2的完全集,而1表中匹配的则有值,没有匹配的则以null值取代。

1 2 select * from table a right join table b on table a.id= table b.id

执行以上sql输出结果如下:

id name address
1 google 美国
5 null 中国
3 微博 中国
6

四、full outer join

full join 会从左表 和右表 那里返回所有的行。如果其中一个表的数据行在另一个表中没有匹配的行,那么对面的数据用null代替

full outer join语法

1 2 3 4 select column_name(s) from table 1 full outer join table 2 on table 1.column_name= table 2.column_name

full outer join产生1和2的并集。但是需要注意的是,对于没有匹配的记录,则会以null做为值。

1 2 select * from table a full outer join table b on table a.id= table b.id

执行以上sql输出结果如下:

id name address
1 google 美国
2 淘宝 null
3 微博 中国
4 facebook null
5 null 中国
6 null 美国

到此这篇关于sql的各种连接join案例详解的文章就介绍到这了。

未经允许不得转载:搬瓦工中文网 » SQL多表Join实战案例详解:从入门到精通,掌握数据库高效查询技巧