带有WHERE子句的SQL COUNT

时间:2012-07-02 22:59:00

标签: mysql sql select left-join

我对SQL有一个看似简单的问题,我无法搞清楚。假设我有以下表格:

company: 
    company_id
    company_title

users: 
    user_id
    username

company_owners: 
    company_id
    user_id

现在,可以有多个用户作为公司所有者。以下是一些示例数据:

company:
1, "A Company"
2, "B Company"
3, "C Company"

users:
1, "A User"
2, "B User"
3, "C User"

company_owners:
1,1
1,2
1,3
2,3

我正在尝试创建一个查询(MySQL),它根据特定的公司所有者获取company_title以及该公司的所有者数量。所以,例如:

示例查询(英文)run:获取“C User”为其所有者的每家公司的所有者数量:

company_id=1, company_title="A Company", num_owners=3
company_id=2, company_title="B Company", num_owners=1
company_id=3, company_title="C Company", num_owners=0

我试过了:

SELECT COUNT(user_id), company.* FROM `company` 
LEFT JOIN `company_owners` ON company_owners.company_id = company.company_id 
WHERE company_owners.user_id=1 GROUP BY company_id

但是这总是给我一个“1”的所有权,我假设因为它只计算user_id = 1的行。

有没有人有任何想法?如果需要,我可以提供更多细节。

非常感谢!

2 个答案:

答案 0 :(得分:8)

您的WHERE子句应为“此公司的所有者,其user_id = 1”。

SELECT COUNT(user_id), company.*
FROM `company` 
LEFT JOIN `company_owners`
ON company_owners.company_id = company.company_id 
WHERE EXISTS
(
    SELECT *
    FROM company_owners AS co2
    WHERE company_owners.company_id = co2.company_id
    AND co2.user_id = 3
)
GROUP BY company_id

查看在线工作:sqlfiddle

答案 1 :(得分:1)

select company.company_id, company_title, count(*)
from company join company_owners on company.company_id = company_owners.company_id
where exists (select 1 from company_owners co where co.user_id = 1 and co.company_id = company.company_id)
group by company.company_id, company_title