Reputation: 3
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.
I am running this via php (mysqli). How can I improve the performance?
Upvotes: 0
Views: 58
Reputation: 44844
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.
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.
Upvotes: 1