使用两个连接表进行SQL排序

时间:2012-06-27 03:29:35

标签: mysql sql

我有这两个表

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行的ASC

people订单排序answer_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

您可以观察到people id s 4和5没有answer_sheet,但它们应该包含在列表中。 问题:对此必须适当的SQL查询是什么?感谢。

3 个答案:

答案 0 :(得分: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 ......

答案 1 :(得分: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

答案 2 :(得分:0)

SELECT  *
FROM    people
        CROSS APPLY ( SELECT    MAX(date_answered) MaxDate
                      FROM      answer_sheets
                      WHERE     answer_sheets.PersonID = people.ID
                    ) L