如何返回GROUP BY语句的最新记录

时间:2014-02-17 05:10:20

标签: mysql greatest-n-per-group

我有一个表(call_history),它对另一个表(call_detail)中的单个ID有多个记录。我试图返回一个结果,它会为每个ID提供一行,但最近的条目。

因此,例如,针对单个ID对所有行进行分组,但仅返回updated_at字段的最新行(即日期字段)。

到目前为止,我的查询......

SELECT MAX(cd.id) as id, cd.first_name, cd.summary, cd.due_at, ch.body, ch.updated_at 
FROM call_detail as cd 
LEFT JOIN call_history as ch on cd.id = ch.ticket_id 
WHERE cd.status = 'open' AND (NOW() > due_at) 
GROUP BY cd.id HAVING COUNT(*) > 1 
ORDER BY cd.due_at DESC

...返回我想要的'种类',但它给了我最新的条目以对照updated_at字段。我反过来需要它。

更新

我的表格结构如下:

Call_Detail

id | summary | description | due_at              | first_name | last_name
1  | Call 1  | some text   | 20/02/2014 17:00:00 | Joe        | Bloggs
2  | Call 2  | some text   | 18/02/2014 15:00:00 | Fred       | Durst
3  | Call 3  | some text   | 02/03/2014 01:00:00 | Joe        | Bloggs

Call_History

id | ticket_id | body      | updated_at          | first_name | last_name
1  | 1         | update 1  | 17/02/2014 16:00:00 | Joe        | Bloggs
2  | 1         | update 2  | 17/02/2014 16:02:00 | Fred       | Durst
3  | 2         | update 1  | 16/02/2014 12:02:00 | Tom        | Thumb
4  | 1         | update 3  | 17/02/2014 16:10:00 | Joe        | Bloggs
5  | 2         | update 2  | 17/02/2014 01:02:00 | Jack       | Reacher

等...

我需要检索以下输出:

ticket_id | summary | due_at              | first_name | body     | updated_at
1         | Call 1  | 20/02/2014 17:00:00 | Joe        | Update 3 | 17/02/2014 16:10:00
2         | Call 2  | 18/02/2014 15:00:00 | Fred       | Update 2 | 17/02/2014 01:02:00

1 个答案:

答案 0 :(得分:1)

尝试此查询。您需要call_history中的最新记录,因此首先应创建包含这些日期的子查询(请参阅CH_MAX子查询),然后加入ticket_idupdated_at

SELECT cd.id as id, 
       cd.first_name, 
       cd.summary, 
       cd.due_at, 
       ch.body, 
       ch.updated_at 
FROM call_detail as cd 

LEFT JOIN 
 ( SELECT ticket_id, MAX(updated_at) as max_updated_at 
          FROM call_history 
          GROUP BY ticket_id
  ) as CH_MAX ON cd.id = CH_MAX.ticket_id

LEFT JOIN call_history as ch ON cd.id = ch.ticket_id 
                                AND CH_MAX.max_updated_at = ch.updated_at

WHERE cd.status = 'open' AND (due_at<NOW()) 
ORDER BY cd.due_at DESC

SQLFiddle demo