开发者

Return master rows based on detail filter

开发者 https://www.devze.com 2022-12-18 04:55 出处:网络
I have a query where I want to return Master rows based on whether the detail fulfil a certain criteria.

I have a query where I want to return Master rows based on whether the detail fulfil a certain criteria.

For example, I only want to return a particular Master row if AT LEAST one of the Detail rows have SomeProperty = X.

Based on the following predicate:

        predicate = predicate.And(p =>
                                  p.BasketItems.Where(obi => obi.BasketItemTypeID ==
                                                                  (int) BasketType.Refund).Count() > 0);

generates the following SQL:

SELECT COUNT(*)
    FROM [dbo].[BasketItems] AS [t3]
    WHERE ([t3].[BasketId] = [t0].[OrderBasketID]) AND ([t3].[BasketItemTypeID] = 3)
    )) > 0)

Problem with this is it's doing a table开发者_Go百科 scan, so the query takes a while to run.

Just checking that I'm not doing anything crazy and wonder if there's anything that can speed up this query?

Thanks Duncan


select M.basketID, max(M.field1) as field1, max(M.field2) as field2 
from dbo.basketItems as M
Inner join detail on M.basketID = detail.basketID
where detail.basketItemTypeID = '3'
group by M.basketID

(Join master to detail. select all rows where detail has the required criterion. Squish the resulting rows down to 1 per master record.)

0

精彩评论

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