Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL statement to get column based on ID from same table

Tags:

sql

key

The table is like so:

ID Name SupervisorID
1 John NULL
2 Michael NULL
3 David 1

SupervisorID is a foreign key of ID. So, David's SupervisorID of 1 refers to John.

I want to write a statement that retrieves just Name and Supervisor Name, where applicable. So the result-set should look like this:

Name Supervisor
John NULL
Michael NULL
David John

It seems like it should be simple but I can't work it out.

Thank you!

like image 313
Nick Giordano Avatar asked Nov 19 '25 19:11

Nick Giordano


1 Answers

Simply do a self LEFT JOIN:

select t1.name, t2.name
from tablename t1
left join tablename t2 on t2.ID = t1.SupervisorID

(Doing a LEFT JOIN to also return people without a supervisor.)

like image 90
jarlh Avatar answered Nov 22 '25 10:11

jarlh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!