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

时间:2016-03-18 10:05:01

标签: mysql sql

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

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

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

4 个答案:

答案 0 :(得分:0)

有一个相关的子查询来查找user_id""#second last"日期:

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

答案 1 :(得分:0)

根据user_id订单按date的降序排列行号。然后选择行号为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

答案 2 :(得分:0)

试试这个:

 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`

答案 3 :(得分:0)

您可以使用以下查询 -

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&lt; = 2,在此放置您需要用户明智的行数。