简体   繁体   中英

MySQL execution time of subquery

When I am executing the bellow sql query the execution time is 0.0009 seconds

SELECT min(step_number) as min_sn, request_id as rid  
  from request_step  
  where state = 'pending'  
  GROUP BY request_id

But when I am executing the next one the execution time is 0.6511 seconds

select rs0.*
from (SELECT min(step_number) as min_sn, request_id as rid  
  from request_step  
  where state = 'pending'  
  GROUP BY request_id  
  ) rs0

I can not understand why, also the number of records is 59675

This is a bit long for for a comment.

The two should have the same performance if the data does not change . MySQL generally saves to disk for the GROUP BY , so materializing the subquery is not going to have much impact on performance.

If this execute very fast (a fraction of a millisecond), then I can only imagine the following scenario:

  • There is an index on (status, request_id, step_number) .
  • Very, very few rows with status = 'pending' .

status = 'pending' then suggests that the database is changing in real time. That, in turn, suggests that rows or the entire table is being locked. If this is the case, the difference in performance is simply due to other things happening on the system.

I am not guaranteeing that this explains the performance difference. It is just seems like a reasonable explanation for the wide variation in performance times.

In the second version, it appears that you are executing 2 queries.

First

SELECT min(step_number) as min_sn, request_id as rid  
from request_step  
where state = 'pending'  
GROUP BY request_id 

will execute and the results with be gathered.

Then,

select rs0.* from <results> as rs0

will be run against the result set from the first query. This will increase execution time due to MySQL setting up the query, gathering the results and then setting up the next query.

Incidentally, although an index will speed up the first query, there is no opportunity to create an index on the the results and so any attempt at filtering after the first query has run will have significant performance implications for any large dataset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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