Mysql 自连接给出奇怪的结果

Mysql self join gives weird results

我有这个 table 有:

 id|subject          | parent_id
 1 |ladbore          | 2
 2 |quod             | NULL
 3 |cumque           | 6
 4 |ut               | 3
 5 |sed              | NULL
 6 |reprehenderit    | 1
 7 |qui              | 4
 8 |eum              | 6
 9 |deserunt         | 6
10 |et               | 6

现在我创建了一个自连接来获取所有主题,包括父主题的名称,如下所示:

SELECT 
 `subject`. `id`,
 `subject`.`subject` AS `subject_name`,
 `parent`.`subject` AS `parent_name`
FROM
`subjects` AS `subject`
LEFT JOIN
`subjects` AS  `parent`  
ON  
`parent`.`id` = `subject`.`id`;

但是这给了我以下奇怪的结果:

id  subject_name    parent_name
1   labore          labore
2   quod            quod
3   cumque          cumque
4   ut              ut
5   sed             sed
6   reprehenderit   reprehenderit
7   qui             qui
8   eum             eum
9   eserunt         deserunt
10  et              et

为什么会给出错误的结果?

你只是加入了对自己的记录,因为你有 parent.id = subject.id。如果你想在你的 table 中使用树结构,那么你需要 (id, parent_id, ...) 作为字段,并加入 subject.parent_id = parent.id

您的查询应该是

SELECT 
 `subject`. `id`,
 `subject`.`subject` AS `subject_name`,
 `parent`.`subject` AS `parent_name`
FROM
`subjects` AS `subject`
LEFT JOIN
`subjects` AS  `parent`  
ON  
`parent`.`id` = `subject`.`parent_id`;