2015-10-23 89 views
2

我需要總行動ID的計數(電話,會議和任務組)通過用戶名和帳戶的名稱SUM多個計數和集團通過

我試試這個,但總不正確

SELECT count(calls.id) + count(meetings.id) + count(tasks.id) AS 'total', users.user_name AS 'name', GROUP_CONCAT(accounts.name) AS 'accounts' 
FROM accounts, calls, users, meetings, tasks 
WHERE accounts.id = calls.parent_id 
AND calls.assigned_user_id = users.id 
AND accounts.id = meetings.parent_id 
AND meetings.assigned_user_id = users.id 
AND accounts.id = tasks.parent_id 
AND tasks.assigned_user_id = users.id 
GROUP BY name 
+1

您能告訴我們一些樣本數據和預期的輸出嗎? –

+0

GROUP BY名稱,accounts.name? – Mihai

+0

總數如何不正確?你能向我們展示樣本數據,以及你得到的結果是什麼? – mjuarez

回答

1

如果沒有代表性數據進行測試的好處,我的猜測是加入的5個表格已將行數相乘,因此總數不正確。在COUNT()中使用DISTINCT可能會有所幫助,例如

SELECT 
     COUNT(DISTINCT calls.id) 
    + COUNT(DISTINCT meetings.id) 
    + COUNT(DISTINCT tasks.id) AS 'total' 
    , users.user_name AS 'name' 
    , GROUP_CONCAT(DISTINCT accounts.name) AS 'accounts' 
FROM accounts 
     INNER JOIN calls ON accounts.id = calls.parent_id 
     INNER JOIN users ON calls.assigned_user_id = users.id 
     INNER JOIN meetings ON accounts.id = meetings.parent_id 
        AND meetings.assigned_user_id = users.id 
     INNER JOIN tasks ON accounts.id = tasks.parent_id 
        AND tasks.assigned_user_id = users.id 
GROUP BY 
     users.user_name 
; 

注意我已經交換過的WHERE子句更現代的方式加盟的老樣子,你真的應該加入。

另一種可能性是,你的罪名是不正確的,因爲你使用的內部連接這要求兩個表中的數據都存在用於返回行的數據。所以也許你需要一些LEFT OUTER JOIN。

SELECT 
     COUNT(DISTINCT calls.id) 
    + COUNT(DISTINCT meetings.id) 
    + COUNT(DISTINCT tasks.id) AS 'total' 
    , users.user_name AS 'name' 
    , GROUP_CONCAT(DISTINCT accounts.name) AS 'accounts' 
FROM accounts 
     LEFT OUTER JOIN calls ON accounts.id = calls.parent_id 
     LEFT OUTER JOIN users ON calls.assigned_user_id = users.id 
     LEFT OUTER JOIN meetings ON accounts.id = meetings.parent_id 
        AND meetings.assigned_user_id = users.id 
     LEFT OUTER JOIN tasks ON accounts.id = tasks.parent_id 
        AND tasks.assigned_user_id = users.id 
GROUP BY 
     users.user_name 
; 

最後的查詢可能是一個混合的加入,某種內在的和有些人離開。

+0

謝謝!其作品! – NARTONIC

+0

太好了。哪一個工作? (所以當別人看這個時,他們會知道),如果這個答案是正確的,你會介意使用勾號來表示它是? –

+0

Natronic讓我知道這是上面看到的LEFT JOIN版本。 –

0
`SELECT COUNT(calls.id) + COUNT(meetings.id) + COUNT(tasks.id) AS total, GROUP_CONCAT(users.user_name) AS name, GROUP_CONCAT(accounts.name) AS accounts 
FROM accounts JOIN calls ON (accounts.id = calls.parent_id) 
JOIN users ON (calls.assigned_user_id = users.id) 
JOIN meetings ON (meetings.assigned_user_id = users.id) 
JOIN tasks ON (accounts.id = tasks.parent_id and tasks.assigned_user_id = users.id) 
GROUP BY users.user_name, accounts.name`