SQL Multiple COUNT() 来自两个表,在一个 LEFT JOIN 中
Posted
技术标签:
【中文标题】SQL Multiple COUNT() 来自两个表,在一个 LEFT JOIN 中【英文标题】:SQL Multiple COUNT() from two tables, within a LEFT JOIN 【发布时间】:2012-02-23 12:01:50 【问题描述】:我有三个表,我想从其中一个表中选择所有数据,并收集该特定数据行在其他两个表中链接的次数的 COUNT。
所以,从 site_projects 中选择所有数据。然后返回 COUNT of site_project_members WHERE site_projects
.id
= site_project_members
.pid
并返回 COUNT of site_project_tasks WHERE site_projects
.id
= site_project_members
.pid
我希望我是有道理的,对于查询,它看起来是正确的。它查询数据库(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 有人能帮忙吗? 非常感谢
谢谢, 丹
【问题讨论】:
这是因为你聚合错误! MySQL 与其他 RDBMS 不同,不会阻止您像这样运行聚合。基本上你会得到随机值,因为你没有指定GROUP BY
。
【参考方案1】:
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
【讨论】:
工作愉快! :D 非常感谢:)【参考方案2】: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
这确实可以解决问题。
【讨论】:
感谢您的回答,但仍然给出相同的结果:S 嗯,问题出在外连接上……让我想想如何重新设计它。 @DanSpiteri 好的,重新设计完成。 对我有很大帮助。谢谢@dgw以上是关于SQL Multiple COUNT() 来自两个表,在一个 LEFT JOIN 中的主要内容,如果未能解决你的问题,请参考以下文章
Laravel Eloquent Multiple Where with count
csharp 来自http://stackoverflow.com/questions/1122942/linq-to-sql-left-outer-join-with-multiple-join-c