gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:13:17 25 4
gpt4 key购买 nike

我有一个表 (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

...返回我想要的“种类”,但它为我提供了 update_at 字段中最旧的条目。我需要相反的方式。

更新

我的表结构如下:

调用详细信息

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

通话历史记录

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

最佳答案

尝试这个查询。您需要 call_history 中的最新记录,因此首先应使用这些日期创建子查询(请参阅 CH_MAX 子查询),然后使用 ticket_id 进行 JOIN 并updated_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

关于mysql - 如何返回 GROUP BY 语句的最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com