Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize a TSQL query?

"activity" is a bit field. I need to set it to true if one of the rows with this client_id has value true

SELECT c.client_id, u.branch_id, a.account_id, activity
FROM Clients c INNER JOIN 
      accounts a ON c.id=a.client_id INNER JOIN uso u ON a.uso_id = u.uso_id,
     (SELECT MAX(CONVERT(int,accounts.activity)) as activity, client_id
       FROM accounts GROUP BY client_id) activ
WHERE activ.client_id = c.id

This query executes about 2 minutes. Please help me to optimize it.

like image 871
DmitryB Avatar asked Oct 11 '22 10:10

DmitryB


1 Answers

Seems activity field is a BIT and you cannot do a MIN or MAX on it.

Instead of this, use TOP:

SELECT  c.client_id, u.branch_id, a.account_id,
        (
        SELECT  TOP 1 activity
        FROM    accounts ai
        WHERE   ai.client_id = c.id
        ORDER BY
                activity DESC
        )
FROM    clients c
JOIN    accounts a
ON      c.id = a.client_id
JOIN    uso u
ON      a.uso_id = u.uso_id

Create an index on accounts (client_id, activity) for this to work fast.

You may want to read this article:

  • Minimum and maximum on bit fields: SQL Server
like image 97
Quassnoi Avatar answered Oct 13 '22 09:10

Quassnoi