POSTGRE如何从分层表

时间:2016-07-26 02:30:39

标签: mysql database postgresql

如何选择父ID的分层表? 我有这样一张桌子

+-----------+------------+-------------+
| id        | parent_id  | name        |
+-----------+------------+-------------+
|1          | 0          | a           |
+-----------+------------+-------------+
|2          | 1          | a1          |
+-----------+------------+-------------+
|3          | 0          | b           |
+-----------+------------+-------------+
|4          | 3          | b1          |
+-----------+------------+-------------+
|5          | 3          | b2          |
+-----------+------------+-------------+

我希望像这样显示表格

+-----------+------------+-------------+
| id        | name       | parent      |
+-----------+------------+-------------+
|1          | a          | NULL        |
+-----------+------------+-------------+
|2          | a1         | a           |
+-----------+------------+-------------+
|3          | b          | NULL        |
+-----------+------------+-------------+
|4          | b1         | b           |
+-----------+------------+-------------+
|5          | b2         | b           |
+-----------+------------+-------------+

是否可以像这样创建选择?任何人都知道如何在Postgre或MySQL中创建它,请给我一些建议,

1 个答案:

答案 0 :(得分:1)

只需使用left join

select t1.id, t1.name, t2.name as parent
from yourtable t1
left join yourtable t2
on t1.parent_id = t2.id
order by t1.id

Demo Here