简体   繁体   中英

Very slow subquery in MySQL

I have two tables A and B (names are abstracted). Both table A and table B have a column called date. Table A has about 3 million rows, with column date indexed. Table B has about 1 million rows.

I have the following query running very slowly (about 20 seconds):

SELECT * FROM A WHERE A.date > (select MAX(date) FROM B)

However, if I run the subquery separately first, it's very fast. And if I substitute the date into the main query, it's also super fast as the data in table A is indexed.

I have seen that this could be an issue if "IN" clause is used. But my query doesn't use IN. Can someone help explain why this is slow?

Thank you!

Move your subquery into the from clause as a derived table and join it to table A without a join condition:

SELECT * FROM A, (select MAX(date) AS mdate FROM B) AS T WHERE A.date > T.mdate

This way you can be sure that the subquery is calculated only once. If A.date is indexed as you wrote, this should speed-up your query. In the current form, I believe the subquery is executed for each record separately.

How many time take select MAX(date) AS mdate FROM B alone?

You can probably save a lot of second if you have an index in B .date too

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