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 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 に答える
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 に答える