sql server join联结

join学习起来有点乱,现做如下整理:

table A

id abc
1 a
2 b
3 c
4 d

table B

id abc
1 e
2 a
3 f
4 c

    --join或者inner join (内连接、等值连接):只返回两个表中连接字段相等的行。

  --select * from  A inner join B on A.abc=B.abc

id abc id1 abc1
1 a 2 a
3 c 4 c

  --left join(左连接) :返回A表中所有的记录以及B表中连接字段相等的记录,没有匹配的则以null值取代。

  --select * from  A left join B on A.abc=B.abc

id abc id1 abc1
1 a 2 a
2 b null null
3 c 4 c
4 d null null

  --right join(右连接):返回B表中所有的记录以及A表中连接字段相等的记录,没有匹配的则以null值取代。

  --select * from  A right join B on A.abc=B.abc

id abc id1 abc1
null null 1 e
1 a 2 a
null null 3 f
2 c 4 c

   --full join(外连接、全连接):返回两个表中的行:left join + right join。对于没有匹配的记录,则会以null做为值。

  --select * from  A full join B on A.abc=B.abc

Venn diagram of SQL cartesian join        

id abc id1 abc1
1 a 2 a
2 b null null
3 c 4 c
4 d null null
null null 1 e
null null 3 f

    --先按照A表中的记录一条一条到B表找匹配项,没有则用null代替。

    --再按照B表中的记录一条一条到A表找匹配项,没有则用null代替。

    --排除重复的记录,则为最后结果

  --cross join:结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数。

 
要么生,要么死
原文地址:https://www.cnblogs.com/llljpf/p/6510546.html