SQL LEFT JOIN中的两个表的多个COUNT()

时间:2012-01-31 18:47:16

标签: sql join count

我有三个表,我想从其中一个表中选择所有数据,并且还收集另外两个表中特定行数据链接的COUNT次。

因此,从site_projects中选择所有数据。然后返回一个COUNT的site_project_members WHERE site_projectsid = site_project_memberspid并返回一个COUNT的site_project_tasks WHERE 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.但它们不是:S任何人都可以提供帮助吗? 非常赞赏

谢谢, 丹

2 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:4)

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

这应该真的有用。