我有这三张表
people
============
id, name
,
surveys
============
id, org_id
和
answer_sheets
============
id, person_id, survey_id, answer, date_answered
person_id
和survey_id
是来自people.id
和surveys.id
的外键
现在,我想做的是根据最新的 answer_sheets.date_answered
对 people
进行排序(我们可以得出一项调查
AND people
行可以有许多 answer_sheets
),给定 surveys.org_id
假设我们有表格
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
我想根据 people
行的最新 answer_sheets.date_answered
按 ASC
顺序对 people
进行排序org_id
= 1
输出将是
=============
id name last_date_answered
4 Person4 NIL
5 Person5 NIL
3 Person3 JUN 17
2 Person2 JUN 18
1 Person1 JUN 19
您可以观察到 id
为 4 和 5 的 people
在调查
中没有 answer_sheet
org_id
= 1 但它们应该包含在列表中。
问题:为此,适当的 SQL 查询必须是什么?谢谢。
最佳答案
这个查询更简单:
SELECT
p.id,
p.name,
t.last_date_answered
FROM people p
LEFT JOIN (
SELECT
a.person_id,
MAX(a.date_answered) as last_date_answered
FROM answer_sheets a
INNER JOIN surveys s ON a.survey_id = s.id
WHERE s.org_id = 1
GROUP BY a.person_id) t ON p.id = t.person_id
ORDER BY t.last_date_answered;
UNION
也很强大,但这里 LEFT JOIN
不太冗长。
关于mysql - 使用 3 个连接表进行 SQL 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11219450/