2009-02-20 89 views
1

晨間:選擇項目,和家長的選擇名稱

表結構:

id | name | parent_id 

我要運行ID的查詢,而且還返回該項目的PARENT_ID和ID的名稱以及。

爲了更好地解釋

SELECT id, name FROM sections 

...然後爲每個ID,返回使用 「PARENT_ID」 列其父的ID和名稱。

我試圖進入一個數組這樣的:

[0] 
    [id] 
    [name] 
    [parent_id] 
    [parent_name] 

回答

5

這應該工作:

SELECT s.id, s.name, s.parent_id, p.name as parent_name 
FROM sections s LEFT JOIN sections p ON s.parent_id = p.id 

基本上你只是想加入該錶針對其自身並在名稱字段作爲帶父母的名字。

1
SELECT a.id, a.name, b.id as parent_id, b.name as parent_name 
FROM sections a 
INNER JOIN sections b on a.parent_id = b.id 

(也可以做,如果有節點沒有父母外連接)

1

剛剛加入該表本身

類似:

SELECT child.id,child.name ,child.parent_id,parent.name AS父母名稱 FROM tablename child LEFT JOIN tablename parent ON child.parent_id = parent.id

1

is doi加入一個比簡單的子查詢更有效的加入?

select id as childID , name as childName, parent_id as pid, (select id from sections where id = pid) as parentID, (select name from sections where id = pid) as parentName from sections; 

更大的問題是,這是不遞歸的......我很好奇,怎麼一會去獲取這個增長循環往復的是多代關係。

+0

在這種情況下,聯接應該更快(特別是在大型結果集上)。你是對的,但你不能輕易找到這種類型的計劃的盛大父母/孩子。爲此,您可能需要遞歸,或者您可以查看嵌套集(Google:sql嵌套集模型) – 2009-02-21 00:18:26

0

你可以有一個像::

1>

Select id as id, name as id_name, (Select id from sections where id=parent_id) as parent_id, (Select name from sections where id=parent_id) as parent_name 
from sections where ..... 

2>

Select child.id, child.name, parent.id, parent.name 
from sections child 
inner join sections parent on (parent.id=child.parent_id) 
where ..... 

可以實現任何一個,但我更喜歡第二一個..

許多解決方案