2013-01-23 78 views
1

我有一个MySQL查询与连接,计数和使用总和的问题。 环境可在这里:http://sqlfiddle.com/#!2/38e813/5MySQL查询没有按预期工作

我的目标是选择用户的所有数据,统计他的评论和帖子数,并总结他收到的所有评级。从示例中可以看出,尽管有3条评级记录,但返回的最终评级数为-4(应为-3)。我认为这将需要一些与群体工作?

回答

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,如果你愿意的话)加在一起,并且每个表的两个评分都加在一起。

要获得所有用户的数据,你必须明确列出从用户表中的列在两个0​​和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

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

+0

非常感谢:) – kudlajz