我有一个大的SQL查询,在from子句中有一个嵌套的select。
与此类似:
SELECT * FROM
( SELECT * FROM SOME_TABLE WHERE some_num = 20)
WHERE some_num = 20
在我的SQL查询中,如果我删除外部“some_num”= 20,则需要5倍的时间。 Shouldent这些查询在几乎完全相同的时间运行,如果不是不会有额外的地方慢慢下来?
我不了解sql查询如何工作?
以下是有问题的原始查询
SELECT a.ITEMNO AS Item_No,
a.DESCRIPTION AS Item_Description,
UNITPRICE / 100 AS Retail_Price,
b.UNITSALES AS Units_Sold,
( Dollar_Sales ) AS Dollar_Sales,
( Dollar_Cost ) AS Dollar_Cost,
( Dollar_Sales ) - ( Dollar_Cost ) AS Gross_Profit,
( Percent_Page * c.PAGECOST ) AS Page_Cost,
( Dollar_Sales - Dollar_Cost - ( Percent_Page * c.PAGECOST ) ) AS Net_Profit,
Percent_Page * 100 AS Percent_Page,
( CASE
WHEN UNITPRICE = 0 THEN NULL
WHEN Percent_Page = 0 THEN NULL
WHEN ( Dollar_Sales - Dollar_Cost - ( Percent_Page * c.PAGECOST ) ) > 0 THEN 0
ELSE ( ceiling(abs(Dollar_Sales - Dollar_Cost - ( Percent_Page * c.PAGECOST )) / ( UNITPRICE / 100 )) )
END ) AS Break_Even,
b.PAGENO AS Page_Num
FROM (SELECT PAGENO,
OFFERITEM,
UNITSALES,
UNITPRICE,
( DOLLARSALES / 100 ) AS Dollar_Sales,
( DOLLARCOST / 10000 ) AS Dollar_Cost,
(( CAST(STUFF(PERCENTPAGE, 2, 0, '.') AS DECIMAL(9, 6)) )) AS Percent_Page
FROM OFFERITEMS
WHERE LEFT(OFFERITEM, 6) = 'CH1301'
AND PERCENTPAGE > 0) AS b
INNER JOIN ITEMMAST a
ON a.EDPNO = 1 * RIGHT(OFFERITEM, 8)
LEFT JOIN OFFERS c
ON c.OFFERNO = 'CH1301'
WHERE LEFT(OFFERITEM, 6) = 'CH1301'
ORDER BY Net_Profit DESC
注意两个
WHERE left(OFFERITEM,6) = 'CH1301'
如果我删除外部Where那么查询需要5倍
根据要求,执行计划原谅了糟糕的上传
答案 0 :(得分:1)
索引中的列OFFERITEM,但PERCENTPAGE不是吗?
在内部查询中,您引用这两列,在外部查询中仅引用OFFERITEM。
很难说没有看到执行计划,但可能是外部查询导致优化器运行'索引扫描',而内部查询将导致全表扫描。
另外,你应该修改:
WHERE left(OFFERITEM,6) ='CH1301'
为:
where offeritem like 'CH1301%'
如果在offeritem上有索引,这将允许索引查找。