mysql:一对多给自己加入

时间:2014-03-26 12:12:30

标签: mysql

我有这张桌子:

id   name     parent_id
0    fruit    NULL
1    place    NULL
2    apple    0
3    orange   0
4    beach    1
5    forest   1

我希望得到这样的结果:

id   name    name
0    fruit   NULL
1    place   NULL
2    apple   fruit
3    orange  fruit
4    beach   place
5    forest  place

我试过这个:

SELECT * FROM foobar LEFT OUTER JOIN foobar c ON c.parent_id = c.id

但它不起作用。

2 个答案:

答案 0 :(得分:2)

JOIN c加入c 本身。您必须加入foobar加入SELECT foobar.id, foobar.name, c.name FROM foobar LEFT OUTER JOIN foobar c ON foobar.parent_id = c.id 。试试这个:

{{1}}

答案 1 :(得分:1)

SELECT c.id, c.name, a.name as [parent] FROM foobar a LEFT OUTER JOIN foobar c ON c.parent_id = a.id