如何提高SQL内部联接的性能?

时间:2018-11-06 17:35:02

标签: sql sql-server sql-server-2012

如何提高此查询性能的第二个表CustomerAccountBrand内部联接 需要很长时间。我添加了未使用的非聚集索引。这是可以连接后拆分成两个内部连接吗?请任何人帮助获取该数据。

SELECT DISTINCT 
    RA.AccountNumber, 
    RA.ShipTo,
    RA.SystemCode,
    CAB.BrandCode
FROM dbo.CustomerAccountRelatedAccounts RA  -- Views
INNER JOIN dbo.CustomerAccount CA
    ON RA.RelatedAccountNumber = CA.AccountNumber
    AND RA.RelatedShipTo = CA.ShipTo
    AND RA.RelatedSystemCode = CA.SystemCode 
INNER JOIN dbo.CustomerAccountBrand CAB   ---- Taking long time 4:30 mins
    ON  CA.AccountNumber = CAB.AccountNumber 
    AND CA.ShipTo = CAB.ShipTo 
    AND CA.SystemCode = CAB.SystemCode

ALTER VIEW [dbo].[CustomerAccountRelatedAccounts]
AS
SELECT        
    ca.AccountNumber, ca.ShipTo, ca.SystemCode, cafg.AccountNumber AS RelatedAccountNumber, cafg.ShipTo AS RelatedShipTo, 
    cafg.SystemCode AS RelatedSystemCode
FROM dbo.CustomerAccount AS ca 
    LEFT OUTER JOIN dbo.CustomerAccount AS cafg 
        ON ca.FinancialGroup = cafg.FinancialGroup 
            AND ca.NationalAccount = cafg.NationalAccount
            AND cafg.IsActive = 1
WHERE CA.IsActive = 1

1 个答案:

答案 0 :(得分:0)

根据我的经验,当查询变得更加复杂时,SQL Server查询优化器通常无法选择正确的联接算法(例如,通过视图联接意味着没有索引可供联接)。如果这是这里发生的事情,那么简单的解决方法是添加一个联接提示以将其转换为哈希联接:

SELECT DISTINCT 
    RA.AccountNumber, 
    RA.ShipTo,
    RA.SystemCode,
    CAB.BrandCode
FROM dbo.CustomerAccountRelatedAccounts RA  -- Views
INNER JOIN dbo.CustomerAccount CA
    ON RA.RelatedAccountNumber = CA.AccountNumber
    AND RA.RelatedShipTo = CA.ShipTo
    AND RA.RelatedSystemCode = CA.SystemCode 
INNER HASH JOIN dbo.CustomerAccountBrand CAB   ---- Note the "HASH" keyword
    ON  CA.AccountNumber = CAB.AccountNumber 
    AND CA.ShipTo = CAB.ShipTo 
    AND CA.SystemCode = CAB.SystemCode