gpt4 book ai didi

sql - MySQL中如何为每个topic_id选择最后两条记录

转载 作者:可可西里 更新时间:2023-11-01 06:30:10 26 4
gpt4 key购买 nike

我必须为每个主题选择最后两条记录。

例如:表:消息

id  |  topic_id
------------
1 | 1
2 | 1
3 | 1
4 | 1
5 | 2
6 | 2
7 | 2
8 | 3
9 | 3
10 | 3

我想获取这些行:

 3 1
4 1
6 2
7 2
9 3
10 3

我该怎么做?

最佳答案

SELECT max(id), max(topic_id) FROM msg
GROUP BY topic_id

UNION

SELECT max(id), max(topic_id) FROM msg
WHERE id not in (
SELECT max(id) as id FROM msg
GROUP BY topic_id)
GROUP BY topic_id

关于sql - MySQL中如何为每个topic_id选择最后两条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2596489/

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