我该如何优化以下mysql查询?

时间:2014-08-13 06:52:32

标签: mysql

我想得到每个品牌的金额总和

如何优化查询?

SELECT a1,a2,a3,a4,a5 
    FROM (
      (SELECT SUM(amount) as a1  FROM `category_data` WHERE brand ='brand1' ) AS t1,
      (SELECT SUM(amount) as a2  FROM `category_data` WHERE brand ='brand2' ) AS t2,
      (SELECT SUM(amount) as a3  FROM `category_data` WHERE brand ='brand3' ) AS t3,
      (SELECT SUM(amount) as a4  FROM `category_data` WHERE brand ='brand4' ) AS t4,
      (SELECT SUM(amount) as a5  FROM `category_data` WHERE brand ='brand5' ) AS t5
    )

name    brand     amount
--------------------------
name1   brand1    1000
name2   brand2    2000
name3   brand1    1200 ...........

2 个答案:

答案 0 :(得分:2)

您可以在单个查询中使用CASE语句,而不是运行5个查询

SELECT 
SUM(CASE WHEN brand ='brand1'  THEN amount ELSE 0 END ) a1,
SUM(CASE WHEN brand ='brand2'  THEN amount ELSE 0 END ) a2,
SUM(CASE WHEN brand ='brand3'  THEN amount ELSE 0 END ) a3,
SUM(CASE WHEN brand ='brand4'  THEN amount ELSE 0 END ) a4,
SUM(CASE WHEN brand ='brand5'  THEN amount ELSE 0 END ) a5
FROM `category_data`

同样使用聚合函数而不对它们进行分组会将整个表数据视为一个组,因此您应该查看GROUP BY (Aggregate) Functions

答案 1 :(得分:1)

膝盖反射的答案是确保您有一个覆盖索引,其前导列为brand,并包含amount列,例如:

... ON category_data (brand, amount) 

查询也可以重写

SELECT SUM(IF(t.brand='brand1',t.amount,NULL)) AS a1
     , SUM(IF(t.brand='brand2',t.amount,NULL)) AS a2
     , SUM(IF(t.brand='brand3',t.amount,NULL)) AS a3
     , SUM(IF(t.brand='brand4',t.amount,NULL)) AS a4
     , SUM(IF(t.brand='brand5',t.amount,NULL)) AS a5
  FROM `category_data` t
 WHERE t.brand IN ('brand1','brand2','brand3','brand4','brand5')

这可能会表现得更好,特别是如果MySQL没有使用原始查询的索引,并且正在执行五次category_data表的完整扫描。