1

我对带有连接、计数和使用总和的 MySQL 查询有疑问。环境在这里可用:http ://sqlfiddle.com/#!2/38e813/5

我的目标是选择所有用户的数据,计算他拥有的评论和帖子的数量,并总结他收到的所有评级。尽管从示例中可以看出,即使有 3 条评分记录,返回的最终评分数也是 -4(应该是 -3)。我认为它需要与 group by 进行一些工作?

4

1 回答 1

2

这是我使用派生表(作为 x 和 y)的答案:

select x.id, x.active, x.ip, x.registered, x.username, x.email, x.role, 
   x.posts, y.comments, x.rating + y.rating as rating 
from
   (select u.id, u.active, u.ip, u.registered, u.username, u.email, u.role, 
    count(p.user_id) as posts, ifnull(sum(pr.rating),0) as rating 
    from users u 
    join posts p on p.user_id=u.id
    left join posts_ratings pr on pr.post_id=p.id) as x
join
   (select u.id, u.active, u.ip, u.registered, u.username, u.email, u.role, 
    count(c.user_id) as comments, ifnull(sum(cr.rating),0) as rating 
    from users u 
    join comments c on c.user_id=u.id
    left join comments_ratings cr on cr.comment_id=c.id) as y
on x.username=y.username;

x表获取帖子数和总评分,而该y表获取评论数和总评分。两个表都通过用户名(如果需要,也可以是 user_id)连接,并且每个表的两个评分都加在一起。

x要获取所有用户的数据,您必须在和表中显式列出用户表中的列y
select u.id, u.active, u.ip, u.registered, u.username, u.email, u.role, ... COLS here
然后在最外面的选择(第一行)中执行相同操作:
select x.id, x.active, x.ip, x.registered, x.username, x.email, x.role, ... COLS here

要获取特定用户,WHERE请在表 x、表 y 和最外面的选择上添加子句。

于 2013-01-23T22:56:33.047 回答