SQL表连接,sql表
背景
在上次的自考科目《数据库系统原理》中,已经接触到了关于数据库表连接的一些知识,最近的学习过程中又用到了关于数据库表的连接问题,趁此再跟大家一起回顾一下。
导图总结
首先用一张思维导图概括一下SQL表连接的内容:
对SQL表连接有个大概的了解之后,我们通过一个小例子进一步来学习一下。首先,我建立和两张表:如下
外连接
外连接包括左外连接、右外连接和完整外连接。
左外连接
SQL语句:select * from table1 left join table2 on table1.id=table2.id
右外连接
SQL语句:select * from table1 right join table2 on table1.id=table2.id
完整连接
SQL语句:select * from table1 full join table2 on table1.id=table2.id
内连接
SQL语句:select table1.id,table2.score from table1 inner join table2 on table1.id=table2.id


交叉连接
SQL语句:select * from table1 cross join table2 on table1.id=table2.id

其实,学习就是这样,反反复复,同时通过在一次次的回顾过程中每次都会有不同的收获,一点点加深理解。
select t1.name,t1.x1,t2,x2,t3.x3
from table1 t1
full join table t2 on t1.name = t2.name
full join table3 t3 on t1.name = t3.name
这样足够了
由于表比较多,这个查询比较复杂。其实难点就在于,当同一个ID在两个表中的行数不相同时,怎样返回最大的行数,并且要求每行一一对应还不能重复。
以B表和C表为例。
首先,用row_number()函数分别为B表和C表生成一个辅助列seq(序号)。结果如下
Select *, row_number() over(partition by Id order by Comment, Time) as Seq from B
Id Comment Time Seq
1 c1 t1 1
1 c2 t2 2
1 c3 t3 3
4 c4 t4 1
4 c5 t5 2
4 c6 t6 3
7 c7 t7 1
-- Select *, row_number() over(partition by Id order by Year, Nick) as Seq from C
Id Year Nick Seq
1 y1 n1 1
7 y2 n2 1
接下来用Full Join连接这两个表。
select isnull(TB.Id TC.Id) as Id, Comment,Time,Year,Nick
from
(Select *, row_number() over(partition by Id order by Comment, Time) as Seq from B) as TB
FULL JOIN
(Select *, row_number() over(partition by Id order by Year, Nick) as Seq from C) as TC
on TB.Id = TC.Id and TB.Seq = TC.Seq
结果应该如下:
Id Comment Time Year Nick
1 c1 t1 y1 n1
1 c2 t2 null null
1 c3 t3 null null
4 c4 t4 null null
4 c5 t5 null null
4 c6 t6 null null
7 c7 t7 y2 n2
然后,用同样的方法将结果FULL JOIN 表D。
最后,表A LEFT JOIN 前几步的结果