Mysql Adjacency List Model,我的查询结果不是我想要的

时间:2013-07-26 06:09:59

标签: mysql sql

昨天,我问过this个问题。我决定改变方法,尝试新的东西。在开始之前,请查看下面的表格结构。

我有一个名为People的表格:

id | name |parent_id
---+------+---------
1  | John | 0
2  | Jane | 1
3  | James| 1
4  | Jack | 0
5  | Jim  | 4
6  | Jenny| 4
7  | Mike | 0

所以约翰是简和詹姆斯的父母。树就是这样。

John
-Jane
-James
Jack
-Jim
-Jenny
Mike

问题的不同始于迈克。迈克没有父母或孩子。只是有人孤单。所以当我使用以下查询查询我的表时,我在结果集中看不到Mike

SELECT 
    t1.name as level1, t2.name as level2 
FROM 
    People as t1 
JOIN 
    People as t2 ON t2.parent_id = t1.id
ORDER BY 
    level1, level2

此查询将带有子项的行带到字段level1。

示例:

level1 | level2
-------+-------
John   | Jane
John   | James
Jack   | Jim
Jack   | Jenny

如何在结果中显示迈克?我应该更改我的查询?

2 个答案:

答案 0 :(得分:2)

Mike没有孩子,所以只需将UNION这些人添加到您的查询中即可。另外,您应该使用INNER JOIN代替LEFT JOIN

select * from 
(
    SELECT 
        t1.name as level1, t2.name as level2 
    FROM 
        People as t1 
    JOIN 
        People as t2 ON t2.parent_id = t1.id
    UNION
    select t1.Name as level1, '' as level2 
        from People t1 
        where Parent_id=0 
        and not exists(select 1 from People where Parent_id=t1.Id)

) People 

ORDER BY 
    level1, level2

SQLFiddle demo

答案 1 :(得分:0)

嘿我已经尝试了你的解决方案,我可以看到MIKE在结果集中

请参阅此链接http://sqlfiddle.com/#!2/73f14/1