在mysql查询中计算两个不同的行

时间:2016-09-12 10:02:48

标签: mysql

我有组织。每个组织都可以拥有成员和项目。 我想获得有成员和项目数量的组织列表。 例如,

Organization | Members | Projects | Action
------------------------------------------
Org 1        | 5       | 6        | Delete - Edit
Org 2        | 2       | 9        | Delete - Edit

我正在使用此查询,

SELECT COUNT(m.id) as members, COUNT(p.id) as projects, 
       o.status,o.organization_name,o.logo, o.id as id
from tbl_organizations o 
LEFT JOIN tbl_organization_members m  ON (o.id = m.organization_id) 
LEFT JOIN tbl_projects p ON (o.id = p.organization_id) 
WHERE o.status= 'active' AND o.created_by= 1

但是项目数量的输出等于成员数量。 如何使用查询制作上面的示例?

3 个答案:

答案 0 :(得分:1)

按组织列分组并计算不同的ID

SELECT o.status,o.organization_name, o.logo, o.id as id,
       COUNT(distinct m.id) as members, COUNT(distinct p.id) as projects, 
from tbl_organizations o 
LEFT JOIN tbl_organization_members m  ON (o.id = m.organization_id) 
LEFT JOIN tbl_projects p ON (o.id = p.organization_id) 
WHERE o.status= 'active' 
AND o.created_by= 1
GROUP BY o.status, o.organization_name, o.logo, o.id

答案 1 :(得分:1)

尝试这种方式:

SELECT o.id as id, o.organization_name, cnt_ as members, cnt_p as projects
from tbl_organizations o 
LEFT JOIN (
   SELECT organization_id, COUNT(id) cnt_m
   FROM tbl_organization_members
   GROUP BY organization_id
) m  ON (o.id = m.organization_id) 
LEFT JOIN (
   SELECT organization_id, COUNT(id) cnt_p
   FROM tbl_projects 
   GROUP BY organization_id
) p ON (o.id = p.organization_id) 
WHERE o.status= 'active' AND o.created_by= 1

这样您JOIN已聚合的版本的成员/项目表,以便获得每organization_id个成员/项目的数量。

答案 2 :(得分:0)

您可以共同关联子查询:

SELECT
    o.id as Organization,
    (SELECT COUNT(*) FROM tbl_organization_members WHERE organization_id = o.id) as members,
    (SELECT COUNT(*) FROM tbl_projects WHERE organization_id = o.id) as projects
FROM
    tbl_organizations o
WHERE
    o.status= 'active' AND o.created_by = 1