2016-07-26 70 views
2

如何選擇具有父級ID的層級表? 我有這樣POSTGRE如何從層級表中選擇父級名稱

+-----------+------------+-------------+ 
| 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

只需使用一個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

+0

我只是有一個表 –

+1

是,'自我join',不是嗎? @yuliantosaparudin – Blank

+0

哈哈哈我是多麼愚蠢,謝謝你先生。 JPG –