使用SUM优化选择... CASE

时间:2012-10-29 16:09:02

标签: mysql sql query-optimization sql-optimization

有没有办法优化此查询:

select 
orders_id,
orders_products_id,
sum(CASE products_options_id WHEN 1 THEN products_options_values_id ELSE 0 END) as color,
sum(CASE products_options_id WHEN 2 THEN products_options_values_id ELSE 0 END) as talle

from 
orders_products_attributes 

group by 
orders_products_id

这是EXPLAIN输出:

id  select_type   table                       type   possible_keys   key   key_len   ref     rows   Extra
1   SIMPLE        orders_products_attributes  ALL    NULL            NULL  NULL      NULL  69006  Using temporary; Using filesort

谢谢!

卢西亚诺

1 个答案:

答案 0 :(得分:0)

我建议使用列(orders_product_id,products_options_id,orders_id)为此查询创建覆盖索引。

CREATE INDEX ix_opa_opid_poid_oid
    ON orders_products_attributes (orders_product_id, products_options_id, orders_id)