按总提交选择用户

时间:2009-02-06 01:39:04

标签: mysql

我知道这很容易,但它让我疯了......

我有一个用户表,评论表和图片表。

我想根据提交内容排列前十名用户(他们的评论总数和提交的照片)。

就是这样。

让我感到羞耻。


更新:根据Ed的回答。

这是我的设置:

  • 用户表(user_id,用户名)
  • 图像表(img_id,submittedby_id = users.user_id)
  • 评论表(id,submittedby_id = users.user_id)

和最终查询:

    select submittedby_id, sum(total)
from 
    (select submittedby_id, count(img_id) as total from    
          images group by submittedby_id 
     union 
     select submittedby_id, count(id) as total from 
          comments group by submittedby_id
    ) as x
 group by submittedby_id 
 order by sum(total) desc limit 10;

3 个答案:

答案 0 :(得分:5)

也许有点像这样:

select username, sum(submissions) 
from 
    (select username, count(picture_id) from    
          pictures group by username 
     union 
     select username, count(comment_id) from 
          comments group by username
    )
 group by username 
 order by sum(submissions) desc limit 10;

从概念上概述:

  1. 计算每个表中用户的提交
  2. 联合那些,因此每个用户将从子查询中获得0到2个计数。
  3. 再组一次,将两个计数相加,然后订购,以便最高金额在最高位置。
  4. 希望这有帮助。

答案 1 :(得分:2)

当然是伪代码,但你想要这样的东西:

select 
  u.userid
, count(commentID) + count(photoID) as totalsubmissions 
from users u
left outer 
    join comments c
    on u.userid = c.userid 
left outer 
    join pictures p 
    on u.userid = p.userid 
group by 
    u.userid 
order by 2 desc 
fetch first 10 rows only

答案 2 :(得分:0)

调整Ed的回答:

select submittedby_id, sum(submissions) 
from 
    (select submittedby_id, count(img_id) as submissions from    
          images group by submittedby_id 
     union all
     select submittedby_id, count(id) as submissions from 
          comments group by submittedby_id
    ) as x
 group by submittedby_id 
 order by sum(submissions) desc limit 10

我相信你想在这里做一个联盟,只需联盟可以省略看起来相同的记录(相同的id和提交数)。