T-SQL中是否有“ IN”语句的替代方法?

时间:2018-09-25 04:40:47

标签: sql-server database tsql

请考虑以下代码段:

SELECT 
    vbs.SKUID, SKUName, SUM(vbs.Quantity) AS Qty
FROM   
    BatchStocks AS vbs
WHERE  
    vbs.SKUID IN (Here i have almost 12000 SKU)
    AND vbs.StoreID IN (%q)
    AND vbs.StockType = %n
GROUP BY
    vbs.SKUID, vbs.SKUName

where条件下,我有将近12000 SKUID,这需要很多时间来执行语句。您能建议我如何改善此查询吗?

2 个答案:

答案 0 :(得分:4)

您可以使用EXISTS()

将SKU放入临时表

WHERE  vbs.SKUID IN (Here i have almost 12000 SKU)

更改为

WHERE  EXISTS
       (
           SELECT *
           FROM   #TEMP x
           WHERE  x.SKUID  = vbs.SKUID 
       )

答案 1 :(得分:1)

您也可以使用Inner Join, EXISTS代替IN。 请参考EXISTS查询:

SELECT 
    vbs.SKUID, SKUName, SUM(vbs.Quantity) AS Qty
FROM   
    BatchStocks AS vbs
WHERE  
    EXISTS ( select 1 from #TEMPTABLE t on t.SKUID = vbs.SKUID)
    AND vbs.StoreID IN (%q)
    AND vbs.StockType = %n
GROUP BY
    vbs.SKUID, vbs.SKUName

请在下面查询INNER JOIN:

SELECT 
    vbs.SKUID, SKUName, SUM(vbs.Quantity) AS Qty
FROM   
    BatchStocks AS vbs
    INNER JOIN #TEMPTABLE t on t.SKUID = vbs.SKUID
WHERE  vbs.StoreID IN (%q)
    AND vbs.StockType = %n
GROUP BY
    vbs.SKUID, vbs.SKUName