gpt4 book ai didi

MySQL:选择每个用户的最后x项

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

我有一个表,其中包含系统中每个用户的大量带时间戳的条目:

id (int, PK)
user_id (int, FK)
date (datetime)
description (text)
other columns...

如何选择每个用户的最后 x(例如 2)项?(最后一项,我的意思当然是按日期排序的项目)

最佳答案

有一个相关子查询来查找 user_id 的“倒数第二个”日期:

select t1.*
from tablename t1
where t1.date >= (select date from tablename t2
where t2.user_id = t1.user_id
order by date desc
limit 1,1)

如果您希望每个用户最后 3 行,请调整为 LIMIT 2,1

关于MySQL:选择每个用户的最后x项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36081467/

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