2013-10-14 26 views
3
"id" "parent" "name" 
"1"  "0"   "Books" 
"2"  "1"   "Crime Fiction" 
"3"  "2"   "Death On the Nile" 

從類似上述情況,我該怎麼選擇父行的namechild的姓名。這裏將提供子行的名稱。我需要獲得父母的name選擇父行,當子行提供

所需的輸出:

@id = 3 

Crime Fiction //This is the name of the parent row - in this case 2 
    Death on the Nile // This is the name of the row who's id was supplied. 

如何在同一個表中選擇做什麼?

回答

6
select parent.name, child.name 
from your_table child 
left join your_table parent on child.parent = parent.id 
where child.id = 3 
+0

太棒了,謝謝:) –

1
select t1.name, t2.name as parent_name from tablename t1 join tablename t2 
on t1.id=t2.parent where t1.id=3 
1
SELECT (CASE WHEN p.name IS NULL THEN "???" ELSE p.name END) AS name 
FROM <your_table> c LEFT JOIN <your_table> p 
ON c.parent = p.id 
WHERE c.name = <yourname> 
LIMIT 1; 

此查詢將返回父名稱爲給定的孩子的名字,或 「???」如果找不到父母。