2012-01-31 130 views
10

我有三個表,我想從一個表中選擇所有數據,並且還要收集特定數據行鏈接次數的COUNT另外兩張桌子。SQL在兩個表中的多個COUNT(),在一個LEFT JOIN中

因此,從site_projects中選擇所有數據。然後返回一個COUNT的site_project_members WHERE site_projectsid = site_project_memberspid,並返回COUNT個site_project_tasks,其中site_projectsid = site_project_memberspid

我希望我是有道理的,對於查詢,它看起來是正確的。並且它沒有問題地查詢數據庫(MySQL)。 以外,它返回兩個計數的總和。 (請參閱下表結構)

site_projects

id | title  | desc  | start  | deadline | progress 

1 | Project 1 | a project | 1321748906 | 1329847200 | 20 

site_project_members

id | pid | uid | img | hidden 
1 | 1 | 1 | 1 | 0 
2 | 1 | 2 | 2 | 0 

site_project_tasks

id | pid | desc | completed 
1 | 1 | Task 1 | 1 
1 | 1 | Task 2 | 0 

這裏是我的查詢:

SELECT p.`id`, p.`title`, p.`desc`, p.`progress`, p.`start`, p.`deadline`, COUNT(m.`id`) as `members`, COUNT(t.`id`) as `tasks` FROM `site_projects` p LEFT JOIN `site_project_members` m ON p.`id`=m.`pid` LEFT OUTER JOIN `site_project_tasks` t ON p.`id`=t.`pid` ORDER BY p.`id` ASC 

結果我得到的是:

id | title  | desc  | progress | start  | deadline | members | tasks 
1 | Project 1 | a project | 20  | 1321748906 | 1329847200 | 4  | 4 

無論是「4」的值應該爲2。然而,它們不是:能小號任何幫助? 大加讚賞

感謝, 丹

+0

這是因爲您在彙總錯誤!與其他RDBMS不同,MySQL不會阻止你像這樣運行聚合。基本上你會得到隨機值,因爲你沒有指定一個「GROUP BY」。 – JNK 2012-01-31 18:52:16

回答

21
SELECT p.id , p.title , p.desc , p.progress , p.start , p.deadline , 
    COALESCE(m.cnt, 0) AS members, 
    COALESCE(t.cnt, 0) AS tasks 
FROM site_projects p 
LEFT JOIN 
    (SELECT pid, COUNT(*) AS cnt FROM 
    site_project_members 
    GROUP BY pid) m 
ON p.id = m.pid 
LEFT JOIN 
    (SELECT pid, COUNT(*) AS cnt FROM 
    site_project_tasks 
    GROUP BY pid) t 
ON p.id = t.pid 
ORDER BY p.id ASC 
+0

工程! :D非常感謝你:) – 2012-01-31 19:07:17

+0

非常感謝,這讓我省下了我的查詢。 SELECT COALESCE(posts.total,0)AS posts,COALESCE(likes.total,0)AS likes,COALESCE(comments.total,0)AS評論,'user'。*,'company'.name FROM'user' INNER JOIN'company' ON user.company_id = company.id INNER JOIN(SELECT user_id,count(*)AS FROM'feed' GROUP BY user_id)posts ON_user_id = user.id INNER JOIN(SELECT user_id ,count(*)AS FROM'comment' GROUP BY user_id)評論ON comments.user_id = user.id INNER JOIN(SELECT user_id,count(*)AS FROM'like' GROUP BY user_id)likes ON likes.user_id = user.id; – 2014-09-24 04:26:14

3
SELECT p.`id`, p.`title`, p.`desc`, p.`progress`, p.`start`, p.`deadline`, 
    (SELECT COUNT(*) FROM site_project_members m WHERE p.`id`=m.`pid`) AS `members`, 
    (SELECT COUNT(*) FROM site_project_tasks t WHERE p.`id`=t.`pid`) AS `tasks` 
FROM `site_projects` p 
ORDER BY p.`id` ASC 

這確實應該做的伎倆。

+0

感謝您的回答,但它仍然給出了相同的結果:S – 2012-01-31 18:55:16

+0

嗯,問題在於外部連接...讓我想想如何重新設計它。 – dgw 2012-01-31 19:00:05

+0

@DanSpiteri好的,重新設計完成。 – dgw 2012-01-31 19:07:34