简体   繁体   中英

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.

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:

Join is expensive. Instead of Join, use memcache and make separate requests.

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