簡體   English   中英

where 條件中的 SQL IN 子句導致大數據的性能問題

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

以下查詢在我的數據庫中運行良好,但在客戶數據庫中產生了巨大的性能問題。 我知道我在給我這個問題的 where 條件中使用了 IN 子句。 但我不知道如何解決這個問題。

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'))

我知道 where 子句中的第二個條件導致了問題。 我在各種帖子中都看到使用 join 可以解決這個問題。 但我不知道如何在 where 條件中使用 join 。 或者有沒有其他相同的方法。

請幫忙。

您的問題很可能是“捕獲所有查詢”。 您可以嘗試將案例拆分如下

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) 

可以嘗試類似的東西

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

LEFT JOIN 並在 where 條件下過濾掉空值。

EXISTS 而不是 IN。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM