Home > Enterprise >  WHERE HAVING COUNT(*) Very slow query
WHERE HAVING COUNT(*) Very slow query

Time:07-05

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

CodePudding user response:

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?

CodePudding user response:

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

CodePudding user response:

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().

  • Related