[英]How To Optimize This Complex MySql Query
我有這個查詢
SELECT id, number, count, name FROM temp AS t1 WHERE (SELECT COUNT(*) FROM temp AS t2 WHERE t2.number = t1.number AND t2.count > t1.count ) = 0 AND id NOT IN (SELECT id FROM temp WHERE count < 3)
它的當前執行時間太長,表temp有15萬行,並且在增加。
我正在通過php(mysqli)運行它。 如何提高性能?
在您的查詢條件
AND id NOT IN (SELECT id FROM temp WHERE count < 3)
可以用作
and `count` < 3
您還可以使用exists
策略轉換子查詢,並最終添加一些索引。 https://dev.mysql.com/doc/refman/5.5/en/subquery-optimization-with-exists.html
select id,number,`count`,name from temp t1
where t1.`count` < 3
and not exists(
select 1 from temp t2
where t2.number = t1.number AND t2.count > t1.count
)
如果尚未建立索引,可能需要
alter table temp add index cnt_idx(`count`);
alter table temp add index number_idx(`number`);
在應用索引之前,請確保對表進行備份。
您始終可以使用explain select
來檢查查詢的運行狀況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.