SQL:从具有大量行数的两个用户标识中选择所有行

时间:2013-09-19 20:23:20

标签: mysql sql

我想从拥有最多行数的两个用户获取所有行,即在日志表中具有最大活动的两个用户。

我只找到了下一个解决方案:首先,获取每个用户的行数,将其限制为2:

SELECT userid, count(*) AS n_of_rows FROM my_table GROUP BY userid LIMIT 2;

然后,从源代码我查询数据库(例如Python),查询数据库以获取每个用户的行:

SELECT * FROM my_table where userid = $userid

考虑到SQL语言本身和数据库性能,它是最好/最优雅的解决方案吗?

谢谢!

3 个答案:

答案 0 :(得分:3)

我认为您正在寻找的是

select * from my_table where userid in
(select userid from my_table
 group by userid
 order by count(*) desc
 limit 2)

答案 1 :(得分:2)

要获取行并保持顺序,请使用带有聚合的join

select t.*
from my_table t join
     (select userid, count(*) as cnt
      from my_table
      group by userid
      order by count(*) desc
      limit 2
     ) top2
     on t.userid = top2.userid
order by top2.cnt desc, userid;

答案 2 :(得分:0)

试试这个:

SELECT TOP 2 userid, count(*) AS n_of_rows 
FROM my_table 
GROUP BY userid 
ORDER BY count(*) desc