我有以下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(*)...在这种情况下不起作用
答案 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`)