我有這三個表SQL 3級聯接表排序
people
============
id, name
,
surveys
============
id, org_id
和
answer_sheets
============
id, person_id, survey_id, answer, date_answered
person_id
和survey_id
從people.id
和外鍵現在
,我想要做的是,以排序在這樣people
使其基於最新answer_sheets.date_answered
給出的surveys.org_id
(我們可以得出一個surveys
和people
行可以有很多answer_sheets
)比方說,我們有表
people
============
id name
1 Person1
2 Person2
3 Person3
4 Person4
5 Person5
surveys
============
id org_id
1 1
2 1
3 2
4 2
answer_sheets
=============
id person_id survey_id answer date_answered
1 1 1 string JUN 13
2 2 1 string JUN 15
3 3 2 string JUN 17
4 2 2 string JUN 18
5 1 2 string JUN 19
6 3 3 string JUN 20
7 2 3 string JUN 25
8 4 3 string JUN 27
9 4 4 string JUN 27
,我想根據在ASC
以訂購行中有org_id
= 1
調查的最新answer_sheets.date_answered
輸出將
=============
id name last_date_answered
4 Person4 NIL
5 Person5 NIL
3 Person3 JUN 17
2 Person2 JUN 18
1 Person1 JUN 19
你可以觀察到people
與id
第4和第5沒有在surveys
的answer_sheet
與org_id
= 1,但他們應列入清單。 問題:什麼是適當的SQL查詢?謝謝。
這功課嗎? – tsells