请考虑以下代码段:
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,这需要很多时间来执行语句。您能建议我如何改善此查询吗?
答案 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