Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select parent row from same table when a child row is supplied

Tags:

sql

mysql

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

From something like the above, how can I select the name of the parent row along with the name of the child. Here, the name of the child row will be supplied. I need to get the name of the parent.

Desired output:

@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.

How is selecting inside the same table done?

like image 610
Norman Avatar asked Dec 25 '22 19:12

Norman


1 Answers

select parent.name, child.name
from your_table child
left join your_table parent on child.parent = parent.id
where child.id = 3
like image 87
juergen d Avatar answered Dec 28 '22 08:12

juergen d