我在使用连接,计数和使用sum的MySQL查询时遇到问题。 环境可在此处获取:http://sqlfiddle.com/#!2/38e813/5
我的目标是选择所有用户的数据,计算他的评论和帖子数量,并总结他收到的所有评分。从示例中可以看出,尽管有3条评级记录,但最终评级数为-4(应为-3)。我认为它需要与group by一起工作吗?
答案 0 :(得分: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
表中明确列出users表中的列:
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
子句。