[英]MySQL: Select last x items of each user
我的系统中的每个用户都有一个带有很多时间戳条目的表:
id (int, PK)
user_id (int, FK)
date (datetime)
description (text)
other columns...
如何选择每个用户的最后x(例如2个)项目? (对于最后一项,我的意思是当然是按日期对desc进行排序的项)
有一个相关的子查询来查找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
。
根据date
的降序给出基于user_id
的行号。 然后选择行号为1和2的行。
询问
select t1.id, t1.user_id, t1.`date`, t1.`description` from
(
select id, user_id, `date`, `description`,
(
case user_id when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := user_id end
) as rn
from ypur_table_name t,
(select @curRow := 0, @curA := '') r
order by user_id, `date` desc
)t1
where t1.rn in (1, 2); -- or change t1.rn <= 2. Change 2 accordingly
尝试这个:
SELECT t.id, t.user_id, t.`date`, t.`description`
FROM (SELECT id, user_id, `date`, `description`
FROM mytable t1
ORDER BY t1.date desc
LIMIT X) t --Change x to the number which you want.
GROUP BY t.id, t.user_id, t.`date`, t.`description`
您可以在下面的查询中使用-
SELECT x.*
FROM (SELECT t.*,
CASE
WHEN @category != t.user_id THEN @rownum := 1
ELSE @rownum := @rownum + 1
END AS rank,
@category := t.user_id AS var_category
FROM your_table AS t
JOIN (SELECT @rownum := NULL, @category := '') r
ORDER BY t.user_id,t.date DESC,t.id) x
WHERE x.rank<=2;
注意:x.rank <= 2,在此处放置用户需要多少行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.