简体   繁体   中英

Why does this query take all day to run on mysql?

I have the following query that takes several minutes to run on mysql:

SELECT * FROM
  sys_quote_master AS g1
JOIN (SELECT order_id, order_base_id, max(order_date_last_revised) as mostrecent 
  FROM sys_quote_master group by order_base_id) AS g2
ON g2.mostrecent = g1.order_date_last_revised
ORDER BY g1.order_id;

The query runs for several minutes and eventually I get this error:

Incorrect key file for table '/tmp/#sql_4f0_1.MYI'; try to repair it

Can someone please help me and tell me what is wrong?

If you EXPLAIN PLAN, I think you'll see that the inner SELECT has to do a TABLE SCAN to find the max(order_date_last_revised).

I wonder if the subselect would be faster if you used a GROUP BY and HAVING?

http://www.java2s.com/Code/SQL/Select-Clause/GROUPandHAVINGwithsubquery.htm

Ask EXPLAIN PLAN to tell you if I'm correct.

I havent tested this, but try to change the query to

SELECT *
FROM sys_quote_master g3
WHERE (g3.order_id, g3.order_base_id) IN (
    SELECT g2.order_id, g2.order_base_id
    FROM sys_quote_master g2
    group by order_id, order_base_id
    having max(order_date_last_revised) = (
        select g1.order_date_last_revised
        from sys_quote_master g1
        where g2.order_id = g1.order_id
        and g2.order_base_id = g1.order_base_id
    )
);

This is assuming you have an indexed unique key at (order_id, order_base_id), also.. maybe you will need to change

having max(order_date_last_revised) = (

to

having max(order_date_last_revised) IN (

hope it helps

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