gpt4 book ai didi

php - MySQL : Order by and Group By combining not giving the latest record

转载 作者:行者123 更新时间:2023-11-29 05:36:32 24 4
gpt4 key购买 nike

使用以下查询,我正在寻找一种解决方案来获取具有某些条件的最新记录。但它给了我第一条记录,而不是最新的。我认为它只考虑小组请多多指教

SELECT * FROM `contacts` WHERE `id_receiver`=1  GROUP BY `id_thread` ORDER BY created DESC

id id_sender id_thread sender_email id_receiver created(datetime)
1 2 2 51 1 2012-03-24 13:44:48
2 4 4 1 5 2012-04-26 13:46:05
3 2 2 51 1 2012-04-09 12:12:30

要求的输出

id   id_sender  id_thread sender_email   id_receiver      created(datetime)
3 2 2 51 1 2012-04-09 12:12:30

我做了一个测试,只是交换 order by 和 group by ,给我一个错误。

任何人都可以看看这个吗?谢谢。

EDIT 编辑问题,忘了写id_thread

最佳答案

当表中没有 id_thread 列时,如何GROUP BY id_thread

SELECT * 
FROM contacts
WHERE id_receiver = 1
--- GROUP BY id_thread
--- removed
ORDER BY created DESC
LIMIT 1 --- only show one row

根据您的评论,您想要的是每个 id_thread 的最新(按 created 排序)行,这是一个不同且更复杂的查询。这种查询甚至有一个标签,名为 [greatest-n-per-group] .

SELECT c.* 
FROM contacts AS c
JOIN
( SELECT id_thread, MAX(created) AS created
FROM contacts
WHERE id_receiver = 1
GROUP BY id_thread
) AS g
ON (g.id_thread, g.created) = (c.id_thread, c.created)
WHERE c.id_receiver = 1

关于php - MySQL : Order by and Group By combining not giving the latest record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10070152/

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