简体   繁体   中英

Extremely Slow Nested mySQL Query

So, I've just begun a new mySQL database with two main tables, bigTable[600,000 lines] and lilTable[8000 lines]. There is an field blId which links the tables, which has been indexed in bigTable.

I want to select all entries from the bigTable that share a blId with any entry from the lilTable that matches certain criterion, but I don't need any other information from that table, so a join seems excessive.

Without further ado, here is my terribly slow query:

SELECT * FROM testdb.bigTable where blId in 
(SELECT blId FROM certtest.lilTable WHERE color LIKE 'blue'); 

This takes ~52 seconds to run on my computer, and still took 50 seconds when the inner query returned 0 results! On the contrary, if I run the inner query separately and manually create a list of acceptable blId's that I put in place of the sub-query, it runs in less than a tenth of a second. What in the blue blazes is going on here?

Edit: So I've found one way to speed it up, wrap it in another, redundant select statement? (Cuts query time down to 0.25 sec) It anyone could explain this behavior, it would be greatly appreciated.

SELECT * FROM testdb.bigTable where blId in 
(SELECT * FROM 
  (SELECT blId FROM certtest.lilTable WHERE color LIKE 'blue') AS why
); 

Try using exists instead:

SELECT bt.*
FROM testdb.bigTable bt
WHERE EXISTS (SELECT 1
              FROM certtest.lilTable lt
              WHERE lt.color LIKE 'blue' AND bt.blID = lt.blId
             ); 

For the purposes of this query, you want an index on lilTable(blId, color) .

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