1

我有这两张桌子

people
============
id, name

answer_sheets
============
id, person_id, answer, date_answered
  • person_id是 people.id 的外键

现在,我想做的是people根据最新的顺序进行排序answer_sheets.date_answered(我们可以得出people一行可以有很多answer_sheets行)

比如说我们有桌子

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  

我想根据一行的people顺序订购ASCpeopleanswer_sheets.date_answered

输出必须是

=============
id  name      last_date_answered
4   Person4   NIL
5   Person5   NIL
1   Person1   JUN 19
3   Person3   JUN 20
2   Person2   JUN 25

您可以观察到peoplewith ids 4 和 5 没有 ananswer_sheet但它们应该包含在列表中。问题:什么必须是适当的 SQL 查询?谢谢。

4

3 回答 3

4

即使没有匹配项也要显示记录,您可以使用LEFT JOIN

SELECT p.id, p.name, MAX(a.date_answered)
FROM people p
LEFT JOIN answer_sheets a on p.id = a.personID
GROUP BY p.id, p.name
ORDER BY MAX(date_answered) ASC

而且,如果您想尝试一下,或者更多地使用它,我制作了一个SQLFiddle ...

于 2012-06-27T03:50:08.787 回答
1
SELECT
  people.id,
  people.name,
  baseview.last_date_answered
FROM (
  SELECT
    person_id,
    MAX(date_answered) AS last_date_answered
  FROM answer_sheets
  ORDER BY IFNULL(MAX(date_answered),'0001-01-01')
  ) AS baseview
  INNER JOIN people ON bseview.person_id=people.id
于 2012-06-27T03:38:24.297 回答
0

SELECT  *
FROM    people
        CROSS APPLY ( SELECT    MAX(date_answered) MaxDate
                      FROM      answer_sheets
                      WHERE     answer_sheets.PersonID = people.ID
                    ) L
于 2012-06-27T07:57:49.763 回答