[英]Optimize query with subquery and join
我的查询
SELECT a.* FROM hm_all a
JOIN ( SELECT post_id, MIN(priceUS_USD) as price FROM hm_all GROUP BY post_id ) b
ON a.post_id = b.post_id AND a.priceUS_USD = b.price
ORDER BY a.post_id ASC LIMIT 0,20
解释
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 PRIMARY a index post_id post_id 4 NULL 1 Using where
1 PRIMARY <derived2> ref key0 key0 9 a.po. 10
2 DERIVED hm_all index NULL post_id 4 NULL 12112
查询工作正常但速度很慢。 我想知道怎么加速?
我建议将其编写为相关子查询:
select a.*
from hm_all a
where a.priceUS_USD = (select min(a2.priceUS_USD)
from hm_all a2
where a2.post_id = a.post_id
)
order by a.post_id
limit 20;
然后为了性能,您需要hm_all(post_id, priceUS_USD)
上的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.