连接查询

来源:互联网 发布:西北大学现代学院网络 编辑:程序博客网 时间:2024/05/29 02:35

1、外连接

1)左连接
返回指定左表的所有行,如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择的列均为空值(null)。

select * from table1 left join table2 on table1.id=table2.id

结果:

id  name   pid   score------------------------------1   lee    1     902   zhang  2     1004   wang   NULL  NULL

2)右连接
返回指定右表的所有行。如果右表的某行在左表中没有匹配行,则在相关联的结果集行中左表的所有选择的列均为空值(null)。

select * from table1 right join table2 on table1.id=table2.id

结果:

id   name  pid  score------------------------------1    lee   1    902    zhang 2    100NULL NULL  3    70

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

select * from table1 full join table2 on table1.id=table2.id

结果:

id   name  pid  score------------------------------1    lee   1    902    zhang 2    1004    wang  NULL NULLNULL NULL  3    70

2、内连接
内联接是用比较运算符比较要联接列的值的联接,只包含满足查询条件的列。

select * from table1 join table2 on table1.id=table2.id

结果:

id  name  pid  score------------------------------1   lee   1   902   zhang 2   100

3、交叉连接(笛卡尔积)
产生联接所涉及的表的笛卡尔积。

select * from table1 cross join table2

结果:

id  name  pid  score------------------------------1   lee   1    902   zhang 1    904   wang  1    901   lee   2    1002   zhang 2    1004   wang  2    1001   lee   3    702   zhang 3    704   wang  3    70
原创粉丝点击