SQL Where子句大大增加了查询时间

时间:2019-05-28 15:53:16

标签: sql sql-server tsql where-clause

我有一个表,可以对其进行一些连接和操作。该表大约有150,000行,如果我全选并运行它,它将在10秒钟后返回。如果我将查询创建到其自己的表中,并过滤掉某个字段为null的所有行,那么查询将需要10分钟才能运行。是应该这样吗?还是有什么办法可以解决?这是查询。

SELECT *
FROM
(
    Select 
     I.Date_Created
    ,I.Company_Code
    ,I.Division_Code
    ,I.Invoice_Number
    ,Sh.CUST_PO
    ,I.Total_Quantity
    ,ID.Total
    ,SH.Ship_City City
    ,CASE WHEN SH.Ship_Cntry <> 'US' THEN 'INT' ELSE SH.Ship_prov END State
    ,SH.Ship_Zip Zip
    ,SH.Ship_Cntry Country
    ,S.CustomerEmail
    from [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices I (nolock)
    LEFT JOIN (SELECT 
                    ID.Company_Code
                    ,ID.Division_Code
                    ,ID.Invoice_Number
                    ,SUM (ID.Price* ID.Quantity) Total
                    FROM [JMNYC-AMTDB].[AMTPLUS].[dbo].Invoices_Detail ID (nolock)
                    GROUP BY ID.Company_Code, ID.Division_Code, ID.Invoice_Number) ID 
            ON I.Company_Code = ID.Company_Code
            AND I.Division_Code = ID.Division_Code
            AND I.Invoice_Number = ID.Invoice_Number
    LEFT JOIN 
        [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].SHIPHIST SH (nolock) ON I.Pickticket_Number = SH.Packslip
    LEFT JOIN 
        [JMDNJ-ACCELSQL].[A1WAREHOUSE].[dbo].[MagentoCustomerEmailData] S on SH.CUST_PO = S.InvoiceNumber

    Where I.Company_Code ='09' AND I.Division_Code = '001'
    AND I.Customer_Number = 'ECOM2X'
    )T
    Where T.CustomerEmail IS NOT NULL -- This is the problematic line
Order By T.Date_Created desc 

1 个答案:

答案 0 :(得分:1)

如果您知道Index Considerations并且对问题点有把握,则可以使用它来进行改进:

USE A1WAREHOUSE;
GO

CREATE NONCLUSTERED INDEX IX_MagentoCustomerEmailData_CustomerEmail
ON [dbo].[MagentoCustomerEmailData] (CustomerEmail ASC);

GO

总共,您需要在ORDER BYWHEREGROUP BYON等部分中使用的列上添加索引。添加索引之前,请确保您已意识到后果。

了解有关索引的更多信息:

  1. https://www.mssqltips.com/sqlservertutorial/9133/sql-server-nonclustered-indexes/
  2. https://www.itprotoday.com/sql-server/indexing-dos-and-don-ts