MySQL选择计数

时间:2011-03-16 11:03:44

标签: mysql count

我正在尝试计算以下查询中至少包含一种产品的公司数量

SELECT count(*)
FROM company c
JOIN product p on c.id = product.company_id
WHERE p.is_deleted = 0
AND c.is_customer = 1
AND c.company_type_id = 5
GROUP by c.id

因此,这显示了所有公司的清单,以及每家公司的产品数量。

我想要实现的是上述结果中的公司数量。

这可以通过以下方式实现:

SELECT count(*)
FROM ( 
    SELECT count(*)
    FROM company c
    JOIN product p on c.id = product.company_id
    WHERE p.is_deleted = 0
    AND c.is_customer = 1
    and c.company_type_id = 5
    GROUP by c.id) AS t1

所以,这给了我正确的结果,但我只是想知道是否有更有效的做事方式。

1 个答案:

答案 0 :(得分:9)

我相信你可以简化它:

SELECT count(distinct c.id)
FROM company c
JOIN product p on c.id = product.company_id
WHERE p.is_deleted = 0
AND c.is_customer = 1
AND c.company_type_id = 5