0

我有一大堆桌子:

Table1: PersonID, A1, A2, A3, ...

Table2: PersonID, B1, B2, B3, ...

Table3: PersonID, C1, C2, C3, ...

Table4: PersonID, D1, D2, D3, ...

...

表 1 很特别,因为它实际上包含所有个人(姓名和个人信息),但所有其他表几乎可以肯定缺少行(一个人根本没有参与该事件)。

我想做的是将所有表连接在一起(通过公共 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

所有这一切都让我记忆力超负荷。我想我以某种方式把我所有桌子的笛卡尔积都拿走了,这让一切都窒息了。有没有好的方法来做到这一点?

提前致谢!

4

2 回答 2

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 连接表单的更多信息。

于 2013-03-12T21:46:52.617 回答
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

是的,你正在使用所有表格的笛卡尔积,然后将其加入其他表格

于 2013-03-12T21:48:14.947 回答