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

SQL select with three tables and foreign keys

I have three tables :

field:

f_id f_start f_end
1 10 20
2 15 25
3 5 10

person :

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

p_id p_name
1 Roger
2 John
3 Alicia

affect :

id fk_field fk_person
1 2 1
2 1 2
3 3 3

And I would like to select the dates and the names associated to. Like this

p_name f_start f_end
Roger 15 25
John 10 20
Alicia 5 10

I’m new to SQL and I don’t know if i have to use JOIN or not… Thanks

>Solution :

You must join all 3 tables on their related columns:

SELECT p.p_name, f.f_start, f.f_end
FROM person p
INNER JOIN affect a ON a.fk_person = p.p_id
INNER JOIN field f ON f.f_id = a.fk_field;

Depending on your requirement you may need LEFT instead of INNER joins, but for this sample data the INNER joins will do.

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