4
"id"    "parent"    "name"
"1"     "0"         "Books"
"2"     "1"         "Crime Fiction"
"3"     "2"         "Death On the Nile"

从类似上面的内容中,我如何选择name父行的名称以及child. 在这里,将提供子行的名称。我需要得到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.

如何在同一张表中进行选择?

4

3 回答 3

8
select parent.name, child.name
from your_table child
left join your_table parent on child.parent = parent.id
where child.id = 3
于 2013-10-14T12:23:18.397 回答
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;

此查询将返回给定子名称的父名称,或“???” 如果它找不到父母。

于 2013-10-14T12:27:07.457 回答
1
select t1.name, t2.name as parent_name from tablename t1 join tablename t2
on t1.id=t2.parent where t1.id=3
于 2013-10-14T12:24:02.013 回答