[英]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.