简体   繁体   English

如何优化此复杂的MySQL查询

[英]How To Optimize This Complex MySql Query

I have this 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)

Its currently taking too long to execute, table temp has 150 000 rows and increasing. 它的当前执行时间太长,表temp有15万行,并且在增加。

I am running this via php (mysqli). 我正在通过php(mysqli)运行它。 How can I improve the performance? 如何提高性能?

In your query the condition 在您的查询条件

AND id NOT IN (SELECT id FROM temp WHERE count < 3)

could be used as 可以用作

and `count` < 3 

You may also convert the subquery with exists strategy and finally adding some indexes. 您还可以使用exists策略转换子查询,并最终添加一些索引。 https://dev.mysql.com/doc/refman/5.5/en/subquery-optimization-with-exists.html 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 
)

The indexing may require if not already there as 如果尚未建立索引,可能需要

alter table temp add index cnt_idx(`count`);
alter table temp add index number_idx(`number`);

Make sure to take a backup of the table before applying the index. 在应用索引之前,请确保对表进行备份。

You can always use explain select to check the query health. 您始终可以使用explain select来检查查询的运行状况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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