"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.
如何在同一张桌子内进行选择?
答案 0 :(得分:6)
select parent.name, child.name
from your_table child
left join your_table parent on child.parent = parent.id
where child.id = 3
答案 1 :(得分:1)
select t1.name, t2.name as parent_name from tablename t1 join tablename t2
on t1.id=t2.parent where t1.id=3
答案 2 :(得分: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;
此查询将返回给定子名称的父名称,或“???”如果找不到父母。