2013-01-23 126 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