有没有办法为某列选择一定数量的行?

时间:2014-04-22 05:50:58

标签: mysql sql

我有这张桌子:

+----+---------+----------+-------+
| id | user_id | other_id | score |
+----+---------+----------+-------+
| 1  | 1       | 1        | 80    |
| 2  | 1       | 2        | 40    |
| 3  | 1       | 3        | 60    |
| 4  | 2       | 2        | 70    |
| 5  | 2       | 4        | 50    |
| 6  | 2       | 3        | 40    |
| 7  | 2       | 5        | 90    |
+----+---------+----------+-------+

我希望按user_id对每个score进行排序,并且每个n仅返回最多user_id(例如2)行。所以我想把结果作为:

+---+---+---+----+
| 1 | 1 | 1 | 80 |
| 3 | 1 | 3 | 60 |
| 7 | 2 | 5 | 90 |
| 4 | 2 | 2 | 70 |
+---+---+---+----+

3 个答案:

答案 0 :(得分:4)

这可以通过使用子选择轻松完成,将计数与相同的表进行比较

SELECT *
FROM   Table1 t
WHERE 
        (
            SELECT  COUNT(*) 
            FROM    Table1  t1
            WHERE t1.user_id = t.user_id AND 
                  t1.score >= t.score
        ) <= 2
ORDER BY t.user_id ASC,t.score DESC

Fiddle Demo

答案 1 :(得分:1)

试试这个:

SELECT
  id, user_id, other_id, score
FROM
  yourtable
WHERE
  score = (SELECT MAX(score) FROM yourtable a 
           WHERE a.user_id = yourtable.user_id 
             AND a.other_id= yourtable.other_id);

答案 2 :(得分:0)

select id , user_id , other_id , score from (select id , user_id , other_id , score,if(@tempvar=user_id,@i:=@i+1,@i:=1) as occurrence, @tempvar:=user_id  from (select * from (select  id , user_id , other_id , score from tablename order by score desc)t order by user_id )tempA,(select @tempvar='',@i=0)tempB)tempc where occurrence<3 group by user_id,occurrence 

我尝试使用您的数据并获得预期的结果。只需将tablename替换为您的表名,然后尝试以上查询