简单加入每组最大值?

时间:2013-02-27 06:54:07

标签: mysql sql select

让我说我有:

USERS:
userid | name
1      | John
2      | Jack

HITS:
id | userid | time
1  | 1      | 50
2  | 1      | 51
3  | 2      | 52
4  | 1      | 53
5  | 2      | 54
6  | 2      | 55

如何获得每位用户的最高两次点击次数。换句话说,修改一下:

select 
   users.userid,  
   h.time 
from  
   users  
left outer join hits h   
on (users.userid = h.userid)

得到这个:

array() {
  [user 1] {
    hit 1 => 50
    hit 2 => 51
  }
  [user 2] {
    hit 3 => 52
    hit 5 => 54
  }
}

我知道正常的加入会给我一切,但是如何将其限制为仅2次点击,有效地获得每位用户的前两次点击?

3 个答案:

答案 0 :(得分:2)

尝试此查询 -

SELECT t.id, t.userid, t.time FROM (
  SELECT h1.*, COUNT(*) pos FROM hits h1
    LEFT JOIN hits h2
      ON h2.userid = h1.userid AND h2.time <= h1.time
  GROUP BY
    h1.userid, h1.time) t
WHERE pos <= 2;

答案 1 :(得分:0)

SELECT  a.userid, 
        a.name, 
        b.time
FROM    users a
        INNER JOIN hits b
            ON a.userid = b.userid
WHERE 
    (
        SELECT  COUNT(*) 
        FROM    hits as c
        WHERE   b.userid = c.userid and 
                b.id >= c.id
    ) <= 2;

答案 2 :(得分:0)

尝试此查询

SET @level = 0;
SET @group = '';

SELECT 
*
FROM (
    SELECT 
    time,
    userid,
    @level := IF(@group = userid, @level+1, 1) AS level, 
    @group := userid as UGroup 
    FROM hits
    ORDER BY userid 
) rs
WHERE level < 3 

Demo