简体   繁体   中英

SQL IN clause in where condition causing performance issue with large data

The following query works fine in my database but it is giving huge performance issues in customer DB. I know that I am using the IN clause in the where condition which is giving me this problem. But I don't know how to fix this.

declare @AccountId int
set @AccountId =  1200
declare @IsLinkedAccountsNotes bit
set @IsLinkedAccountsNotes =1
declare @EventType varchar(100)
set @EventType = ''

SELECT
        u.loginName as InteractionLoginName,
        u.userName as InteractionUserName,
        e.*
    FROM
        lat.events e
        INNER JOIN dbo.MasterEvents me ON me.EventId = e.EventId    
        LEFT JOIN dbo.Users u ON e.UserId = u.ID 
    WHERE
        (me.AccountId = @AccountId OR
        (@IsLinkedAccountsNotes = 1 AND me.AccountId IN (SELECT DISTINCT [number] FROM dbo.Linking_LinkedAccounts WHERE linked_number = @AccountId) AND e.EventType = 'AccountNoteAdded'))

I know that the second condition in where clause is causing the problem. And I have seen in various posts that using a join will solve this problem. But I am not getting how to use join inside where condition. Or is there any other approach for the same.

Please help.

Your problem is likely that this is a "catch all query". You can try splitting the cases out as below

SELECT u.loginName AS InteractionLoginName,
       u.userName  AS InteractionUserName,
       e.*
FROM   lat.events e
       INNER JOIN dbo.MasterEvents me
               ON me.EventId = e.EventId
       LEFT JOIN dbo.Users u
              ON e.UserId = u.ID
WHERE  me.AccountId = @AccountId
UNION ALL
SELECT u.loginName AS InteractionLoginName,
       u.userName  AS InteractionUserName,
       e.*
FROM   lat.events e
       INNER JOIN dbo.MasterEvents me
               ON me.EventId = e.EventId
       LEFT JOIN dbo.Users u
              ON e.UserId = u.ID
WHERE  @IsLinkedAccountsNotes = 1
       AND e.EventType = 'AccountNoteAdded'
       AND me.AccountId IN (SELECT [number]
                            FROM   dbo.Linking_LinkedAccounts
                            WHERE  linked_number = @AccountId
                                   AND [number] <> @AccountId) 

Could try something like

JOIN (SELECT DISTINCT [number] FROM dbo.Linking_LinkedAccounts WHERE linked_number = @AccountId) lla ON lla.number = me.AccountId

LEFT JOIN and filter out null values in where condition.

EXISTS instead of IN.

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