我正在努力优化检索某些产品及其先前记录的定价详细信息的查询。
因为我的 3 个子查询使用 desc 顺序和限制 1 来返回最后记录的价格,并且日志表包含数万行(从长远来看可能包含数百万行),所以它在5秒的区域产生查询结果(大约有3000个产品)。
SELECT products.*,
(SELECT value_new FROM log_actions
WHERE action='edit' AND target_entity='net_price_euro'
AND target_table='products'
AND target_id=products.product_id
ORDER BY log_time DESC LIMIT 1
) AS previous_net_price_euro,
(SELECT value_new FROM log_actions
WHERE action='edit' AND target_entity='retail_sterling'
AND target_table='products' AND target_id=products.product_id
ORDER BY log_time DESC LIMIT 1
) AS previous_retail_sterling,
(SELECT value_new FROM log_actions
WHERE action='edit' AND target_entity='gp'
AND target_table='products'
AND target_id=products.product_id
ORDER BY log_time DESC LIMIT 1
) AS previous_gp
FROM products
WHERE products.deleted IS NULL ORDER BY products.status asc
据我所知,我已将所有相关字段编入索引。在上面运行 EXPLAIN 会返回以下内容:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY products ALL deleted NULL NULL NULL 3192 Using where
4 DEPENDENT SUBQUERY log_actions ref target_entity,target_id,action,target_table target_id 4 products.product_id 4 Using where; Using filesort
3 DEPENDENT SUBQUERY log_actions ref target_entity,target_id,action,target_table target_id 4 products.product_id 4 Using where; Using filesort
2 DEPENDENT SUBQUERY log_actions ref target_entity,target_id,action,target_table target_id 4 products.product_id 4 Using where; Using filesort
我已经阅读了添加 desc 索引可以提高性能,但进一步阅读似乎 MySQL 目前不支持这一点。