Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding relationships with a table and itself

I would like to provide a demo table. The important columns are Fname, Lname, SSN and SuperSSN.

fname lname ssn superssn
Ahmed Ali 112233 223344
Hanaa Sobhy 123456 223344
Kamel Mohamed 223344 321654
Amr Omran 321654 NULL
Edward Hanna 512463 321654
Maged Raoof 521634 968574
Mariam Adel 669955 512463
Noha Mohamed 968574 321654
NULL NULL NULL NULL

Now, the task is:

Find all names of the employees who directly supervised by Kamel Mohamed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I couldn’t wrap my head around a table with a relationship with itself.

This is my best solution, but I feel like I can do better:

SELECT *
FROM employee
WHERE superSSN = 223344 

which is correct, but I don’t want to look in the table and get Kamel’s SSN. Is there a shortcut that I can access the employees that have Kamel as their supervisor without directly getting Kamel’s SSN?
If so, please share!

>Solution :

As you know supervisor’s name, then you could – for example – use a subquery:

select *
from employee
where superSSN = (select SSN
                  from employee
                  where fname = 'Kamel'
                 );
                 

or a self-join:

select a.*
from employee a join employee b on a.superSSN = b.ssn
where b.fname = 'Kamel';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading