分组,拥有和计数

时间:2014-04-07 20:05:19

标签: mysql sql

我有以下sql查询:

    SELECT * FROM `products_groups` `productGroup` 
    LEFT OUTER JOIN `products` `products` ON (`products`.`product_group_id`=`productGroup`.`id`) 
    GROUP BY productGroup.name 
    HAVING (COUNT(products.id) > 0)

您能否告诉我们如何更改查询以返回所有结果中的总行数?

P.S。

SELECT count(*)...在这种情况下不起作用

3 个答案:

答案 0 :(得分:0)

SELECT COUNT (rowTotal) as total 
  FROM (
      SELECT SUM(1) as rowTotal
      FROM `products_groups` `productGroup` 
      LEFT OUTER JOIN `products` `products` 
      ON (`products`.`product_group_id`=`productGroup`.`id`) 
      GROUP BY productGroup.name HAVING (COUNT(products.id) > 0)
  )as groupRows

答案 1 :(得分:0)

COUNT(*)代替SELECT *将不起作用,因为count(*)将应用于每个组。所以你的结果会回来:

第1组 - 11行 第2组 - 2行 等等。

您需要COUNT(*)应用于整个查询而不是组,如下所示:

    SELECT COUNT(*) FROM
    (SELECT 1 FROM `products_groups` `productGroup` 
    LEFT OUTER JOIN `products` `products` ON (`products`.`product_group_id`=`productGroup`.`id`) 
    GROUP BY productGroup.name 
    HAVING (COUNT(products.id) > 0))

答案 2 :(得分:0)

要返回小组总计下的产品总数Union类似查询,请仅排除Group By并使用Inner Join排除没有产品的产品组(作为您的产品) Having子句确实):

SELECT
  productGroup.name as ProductGroup,count(products.id) as ProductCount
FROM `products_groups` `productGroup` 
    LEFT OUTER JOIN `products` `products`
        ON (`products`.`product_group_id`=`productGroup`.`id`) 
GROUP BY productGroup.name 
HAVING (COUNT(products.id) > 0)
UNION ALL
SELECT
    'Total' ProductGroup,count(products.id) ProductCount
FROM `products_groups` `productGroup` 
    INNER JOIN `products` `products`
        ON (`products`.`product_group_id`=`productGroup`.`id`)