join left on多张表,SQL多个COUNT()从两个表,在LEFT JOIN

i have three tables, i want to select all data from one of the tables, and also collect a COUNT of how many times that specific row of data is linked in the other two tables.

So, SELECT all data from site_projects. Then return a COUNT of site_project_members WHERE site_projects.id = site_project_members.pid and also return a COUNT of site_project_tasks WHERE site_projects.id = site_project_members.pid

I hope i'm making sense, to the query, it looks correct. and it querys the database (MySQL) with no problems. Except it returns a sum of both of the counts as both things. (see below the table structures)

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

Here is my query:

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

The result i get is:

id | title | desc | progress | start | deadline | members | tasks

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

Both of the "4" values should be 2. however they are not :S Anyone able to help?

Much Appreciated

Thanks,

Dan

解决方案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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值