I have these two tables
people
============
id, name
and
answer_sheets
============
id, person_id, answer, date_answered
person_idis a foreign key from people.id
Now, what I wanted to do is to sort people in such in order basing it on the latest answer_sheets.date_answered (we can derive that one people row can have many answer_sheets rows)
Say for example we have the tables
people
============
id name
1 Person1
2 Person2
3 Person3
4 Person4
5 Person5
answer_sheets
=============
id person_id answer date_answered
1 1 string JUN 13
2 2 string JUN 15
3 3 string JUN 17
4 2 string JUN 18
5 1 string JUN 19
6 3 string JUN 20
7 2 string JUN 25
and I wanted to order people in ASC order based on a people row’s answer_sheets.date_answered
the output must be
=============
id name last_date_answered
4 Person4 NIL
5 Person5 NIL
1 Person1 JUN 19
3 Person3 JUN 20
2 Person2 JUN 25
You can observe that people with ids 4 and 5 does not have an answer_sheet and yet they should be included in the list.
Question: What must be the appropriate SQL query for this? Thanks.
To get records to display even if there is no match, you can use a LEFT JOIN.
And, if you want to try it out, or play with it more, I made a SQLFiddle…