我有一大堆表:
Table1: PersonID, A1, A2, A3, ...
Table2: PersonID, B1, B2, B3, ...
Table3: PersonID, C1, C2, C3, ...
Table4: PersonID, D1, D2, D3, ...
...
Table1很特别,因为它实际上包含所有个人(姓名和个人信息),但所有其他表几乎肯定都缺少行(一个人根本没有参与该事件)。
我想要做的是将所有表连接在一起(通过公共PersonID),这样任何缺少的属性都将被留空。所以,当然,我想使用外连接。这就是我试过的:
SELECT *
FROM Table1, Table2, Table3, Table4, Table5, Table6
LEFT OUTER JOIN Table2 ON Table1.PersonID = Table2.PersonID
LEFT OUTER JOIN Table3 ON Table1.PersonID = Table3.PersonID
LEFT OUTER JOIN Table4 ON Table1.PersonID = Table4.PersonID
LEFT OUTER JOIN Table5 ON Table1.PersonID = Table5.PersonID
LEFT OUTER JOIN Table6 ON Table1.PersonID = Table6.PersonID
这一切都给了我一个内存过载。我想我以某种方式拿走了我所有桌子的笛卡尔积,这让一切都变得窒息。有没有办法做到这一点?
提前致谢!
答案 0 :(得分:2)
使用此:
SELECT *
FROM Table1
LEFT OUTER JOIN Table2 ON Table1.PersonID = Table2.PersonID
LEFT OUTER JOIN Table3 ON Table1.PersonID = Table3.PersonID
LEFT OUTER JOIN Table4 ON Table1.PersonID = Table4.PersonID
LEFT OUTER JOIN Table5 ON Table1.PersonID = Table5.PersonID
LEFT OUTER JOIN Table6 ON Table1.PersonID = Table6.PersonID
查看 SQL Joins 表格了解详情。
答案 1 :(得分:1)
改变这个:
SELECT *
FROM Table1, Table2, Table3, Table4, Table5, Table6
LEFT OUTER JOIN Table2 ON Table1.PersonID = Table2.PersonID
LEFT OUTER JOIN Table3 ON Table1.PersonID = Table3.PersonID
LEFT OUTER JOIN Table4 ON Table1.PersonID = Table4.PersonID
LEFT OUTER JOIN Table5 ON Table1.PersonID = Table5.PersonID
LEFT OUTER JOIN Table6 ON Table1.PersonID = Table6.PersonID
到此:
SELECT *
FROM Table1
LEFT OUTER JOIN Table2 ON Table1.PersonID = Table2.PersonID
LEFT OUTER JOIN Table3 ON Table1.PersonID = Table3.PersonID
LEFT OUTER JOIN Table4 ON Table1.PersonID = Table4.PersonID
LEFT OUTER JOIN Table5 ON Table1.PersonID = Table5.PersonID
LEFT OUTER JOIN Table6 ON Table1.PersonID = Table6.PersonID
是的,你们拿着所有桌子的笛卡尔积,然后把它加到其他桌子上