SQL 中 ON 子句中连接中的列定位

Column Positioning in Joins in the ON clause in SQL

我有一个 table,其中显示 parents、children 和他们的姓氏。我想将 table 加入到自身中,以查看哪个 child 属于哪个 parent。通常我会使用左连接来列出所有 parents 及其匹配的 children(因为不是每个 child 在这个 [=32= 中都有一个 parent ]) 但是我很困惑为什么我的原始查询不为我做这个?如果有人能很好地解释一下,那就太好了

CREATE TABLE people(
pid int primary key,
childid int null,
lastname varchar(15)
)

INSERT INTO people VALUES(1, NULL,'Red')
INSERT INTO people VALUES(2, 1,'Smith')
INSERT INTO people VALUES(3, 1,'Anderson')
INSERT INTO people VALUES(4, 2,'Griggs')
INSERT INTO people VALUES(5, 3,'Noble')

以下是我认为可以解决问题的原始查询

select p.lastname as Parent, c.lastname as Child
from people p
LEFT JOIN people c
on p.pid = c.childid

本次查询的结果:

+----------+-----------+
|  Parent  |   Child   |
+----------+-----------+
| Red      |  Smith    |
| Red      |  Anderson |
| Smith    |  Griggs   |
| Anderson |  Noble    |
| Griggs   |  (null)   |
| Noble    |  (null)   |
+----------+-----------+

但是我使用下面的查询得到了我想要的结果

select p.lastname as Parent, c.lastname as Child
from people p
LEFT JOIN people c
on c.pid = p.childid

本次查询的结果:

+----------+----------+
|  Parent  |  Child   |
+----------+----------+
| Red      | (null)   |
| Smith    | Red      |
| Anderson | Red      |
| Griggs   | Smith    |
| Noble    | Anderson |
+----------+----------+

如果有人能向我解释为什么两个查询的结果如此不同,那将是一个很大的帮助!谢谢

您似乎在数据架构和查询中调换了 parent 和 child 角色。这就是为什么第二个查询几乎可以正常工作的原因(尽管您错误地标记了答案,但您将它们调回了原位)。按照你的 table 设置方式,每个人只能拥有一个 child。我相信您想说每个人都有一个 parent。 (为简单起见,我忽略了每个人 都应该 有母亲和父亲!)。我已经更改了您的 table DDL 以反映这一点(我还使命名更加明确并明确声明了外键。)

CREATE TABLE people(
personid int primary key,
parentid int foreign key references people(personid) null,
lastname varchar(15)
)

对这段代码应用相同的插入语句。

我还修改了您的第一个查询如下:

select p.lastname as Parent, c.lastname as Child
from people c
LEFT JOIN people p
on p.personid = c.parentid

我翻转了 'c' 和 'p' 引用。这正确地反映了不对称左外连接与 parent 和 child 之间的不对称关系正确对齐。

执行此查询将产生

+----------+----------+
|Parent    |Child     |
+----------+----------+
|NULL      |Red       |
|Red       |Smith     |
|Red       |Anderson  |
|Smith     |Griggs    |
|Anderson  |Noble     |
+----------+----------+

请注意,在您的示例中,第二个查询 returns 正确的关系,但 mis-labels 它们。应该说Red没有parent,却说Red没有child。此修改后的查询更正了这一点。