我知道这很容易,但它让我疯了......
我有一个用户表,评论表和图片表。
我想根据提交内容排列前十名用户(他们的评论总数和提交的照片)。
就是这样。
让我感到羞耻。
更新:根据Ed的回答。
这是我的设置:
和最终查询:
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;
答案 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)
当然是伪代码,但你想要这样的东西:
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和提交数)。