开发者

Is there any optimizations I can do with this statement to get the count of used rows?

开发者 https://www.devze.com 2023-01-03 01:25 出处:网络
Is th开发者_开发知识库ere any optimizations I can do with this statement to get the count of used rows.

Is th开发者_开发知识库ere any optimizations I can do with this statement to get the count of used rows.

Note: The ProductOrderInfo table has over 40 million rows in it.

SELECT @TotalUsed = COUNT(*)
FROM ProductInfo WITH (NOLOCK)
WHERE ProductInfoId IN 
(
    SELECT ProductInfoId FROM ProductOrderInfo WITH (NOLOCK)
);


Use JOIN for such queries:

SELECT @TotalUsed = COUNT(DISTINCT i.ProductInfoId) 
FROM ProductInfo i WITH (NOLOCK) 
JOIN ProductOrderInfo oi WITH (NOLOCK) 
    ON io.ProductInfoId = i.ProductInfoId

Tables should have Indexes by these columns for fast search.


Try this

SELECT @TotalUsed = COUNT(*) FROM ProductInfo WITH (NOLOCK) as p 
WHERE EXISTS ( SELECT ProductInfoId FROM ProductOrderInfo WITH (NOLOCK) 
WHERE ProductInfoId =p.ProductInfoId );


Assuming there are no orphan ProductInfoIds on ProductOrderInfo, the following:

SELECT @TotalUsed = COUNT(DISTINCT ProductInfoId) 
FROM ProductOrderInfo WITH (NOLOCK);

may be faster, as it only accesses one table.

Whichever query is being run, it should run faster if there is an index on ProductInfoID on ProductOrderInfo.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号