简体   繁体   中英

optimize select with SUM … CASE

is there any way to optimize this query:

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

This is the EXPLAIN output:

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

Thanks!

Luciano

I would suggest creating a covering index for this query, using the columns (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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM