2014-09-30 119 views
1

我有一個API,我打電話,我需要來自不同表格的數據很多,所以我使用他們的連接,現在的問題是,雖然我有4個回覆,5個交互數據總是返回20篇和20間相互作用,這是結果:Sql計數返回錯誤的數字

screen_name screen_state replies interactions alerts 
sjerd  0   20  20   0 

我使用此查詢計數記錄和結果:

SELECT u.screen_name, 
      u.screen_state, 
      count(r.id) AS replies, 
      count(i.id) AS interactions, 
      count(a.alerts) AS alerts 
    FROM users u 
    LEFT JOIN reply r ON u.id = r.user 
    LEFT JOIN interactions i ON u.id = i.user_id 
    LEFT JOIN alerts a ON u.id = a.user_id WHERE u.id ='2' 
    GROUP BY u.id, u.screen_state 

有人可以明白爲什麼它返回20,而我只有7行回覆表共有回覆表 和5行交互ns在交互表中總共。 每行是1反應或回覆。

回答

0
SELECT u.screen_name, u.screen_state, 
    count(DISTINCT r.id) AS replies, 
    count(DISTINCT i.id) AS interactions, 
    count(DISTINCT a.alerts) AS alerts 
    FROM users u 
    LEFT JOIN reply r ON u.id = r.user 
    LEFT JOIN interactions i ON u.id = i.user_id 
    LEFT JOIN alerts a ON u.id = a.user_id WHERE u.id ='2' 
    GROUP BY u.id, u.screen_state 
+0

感謝這並獲得成功。你知道爲什麼它會返回更多的行,然後出現在表中,如果我不添加不同的? – 2014-09-30 10:32:03

+0

You'r歡迎,添加r.id,i.id,a.alerts到您的查詢。查看結果集(暫時刪除GROUP)。 – 2014-09-30 10:34:58

3

您的計數總是會給出相同的結果,因爲所有表都在同一級別加入。

你需要做你算作內的子查詢(或什麼 - 我永遠記得正確的術語):

SELECT u.screen_name, 
     u.screen_state, 
     (select count(*) from reply r where u.id = r.user) AS replies, 
     (select count(*) from interactions i where u.id = i.user_id) AS interactions, 
     (select count(*) from alerts a where u.id = a.user_id) AS alerts 
FROM users u 
WHERE u.id ='2'