简体   繁体   中英

WHERE HAVING COUNT(*) Very slow query

I'm trying to run a SQL query which takes 32 sec to complete, any ideas how to run it faster?

SELECT accounts.*
FROM accounts
WHERE accounts.account_id IN (SELECT map.account_id 
                              FROM  map 
                              WHERE map.account_id=accounts.account_id                              
                              HAVING COUNT(*)<2) 
ORDER BY rand() 
LIMIT 1

You could use an inner join to achieve that filtering:

SELECT accounts.*
FROM accounts
INNER JOIN (
    SELECT map.account_id
    FROM map
    GROUP BY map.account_id
    HAVING COUNT(*) < 2
    ) AS m ON accounts.account_id = m.account_id
ORDER BY rand() 
limit 1

I'm not sure why you are ordering by rand or limiting the result to 1 but could it be repetitive execution of this overall query is a performance issue?

Try converting In clause to EXISTS clause -

SELECT accounts.*
  FROM accounts
 WHERE EXISTS (SELECT NULL
                 FROM map 
                WHERE map.account_id=accounts.account_id 
                GROUP BY map.account_id
               HAVING COUNT(*) < 2
               ) 
ORDER BY rand() 
limit 1

Try reversing the condition inside

  • the WHERE clause of the query
  • the HAVING clause of the subquery

The filtering operation will be faster if the output of the subquery is smaller.

SELECT accounts.*
FROM accounts
WHERE accounts.account_id NOT IN (SELECT map.account_id 
                                  FROM map 
                                  WHERE map.account_id=accounts.account_id 
                                  HAVING COUNT(*) >= 2) 
ORDER BY RAND() 
LIMIT 1

Note : Your main source of inefficiency may be easily caused by ORDER BY RAND() .

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