Mysql自连接给出了奇怪的结果

时间:2015-07-10 16:30:29

标签: mysql self-join

我有这张表:

 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

为什么会出错?

2 个答案:

答案 0 :(得分:1)

您只是加入了自己的记录,因为您已经parent.id = subject.id了。如果您想在表格中使用树状结构,则需要(id, parent_id, ...)作为字段,然后加入subject.parent_id = parent.id

答案 1 :(得分:1)

您的查询应该是

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`;