如何使用group by来获得多个结果集?在多列上分组

时间:2011-05-10 13:13:15

标签: php mysql sql database group-by

我有一个名为product的表,其中包含以下数据

pid            brand     color      

1              sony      white
2              casio     gray
3              xoxo      blue
4              samsung   white
5              mvc       silver
6              sony      gray
7              xoxo      red
8              samsung   silver
9              mvc       white

我需要获得属于每个品牌和产品的产品总数。颜色。所以我写了两个不同的查询。

Select count(pid) as total from products group by brand;
Select count(pid) as total from products group by color;

这很好用。但由于我的产品表数据很大,我认为如果我可以通过单个查询实现这一点,效果会更好。有可能吗?

6 个答案:

答案 0 :(得分:2)

您可以简单地获得这两个查询的UNION

( SELECT 1        AS groupType
       , brand    AS grp
       , count(*) AS total
  FROM products 
  GROUP BY brand
)
UNION ALL
( SELECT 2        AS groupType
       , color    AS grp
       , count(*) AS total
  FROM products 
  GROUP BY color
)
ORDER BY groupType
       , grp

如果您想要每种品牌颜色组合的产品数量,您应该将表格按这两个字段分组:

SELECT brand
     , color
     , count(*) AS total
FROM products 
GROUP BY brand
       , color

答案 1 :(得分:0)

可以使用with语句,但在撰写本答案时,MySQL中不提供此功能。

答案 2 :(得分:0)

根据您的桌子实际有多大,首先获得品牌/颜色组合的总数并将它们存储到临时表可能会更便宜,然后查询临时表两次以找到每个标准的最终总计。

就是这样:

-- create a temporary table (omitted)

INSERT INTO temp_table (brand, color, total)
SELECT brand, color, COUNT(*) AS total
FROM products
GROUP BY brand, color

SELECT brand, SUM(total) AS total
FROM temp_table
GROUP BY brand

SELECT color, SUM(total) AS total
FROM temp_table
GROUP BY color

答案 3 :(得分:0)

select 
count(*) over (partition by product), 
count(*) over (partition by color)
from table

答案 4 :(得分:0)

select brand as `group`, count(pid) from products group by brand
union all
select color as `group`, count(pid) from products group by color

答案 5 :(得分:0)

通过两个不同的列分别进行分组会产生两个根本不同的查询,因此从数据库的角度来看,单独运行它们会更容易。我会考虑创建两个索引(一个在品牌上,一个在颜色上)来帮助。