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 ProductInfoId
s 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.
精彩评论