找到更好的查询和LINQ改进

时间:2013-04-09 14:56:39

标签: performance linq sql-server-2008 c#-4.0

从以下SQL Server 2008 R2查询中,我试图找到:

客户及其订单已将某些产品放入订单明细表中。

必须从交叉参考表中匹配此产品。

查询也在查看另一个表(激活),如果它在那里找到任何订单ID,那么它会忽略它们。

这是我的问题:

Select O.CustomerId, O.OrderId
from Orders O 
    inner join Customers C
        on O.CustomerId=C.Customerid
where O.orderid not in
(
    Select orderid 
    from activations
)
and OrderId In
(
    Select orderid 
    from  Orderdetails
    WHERE EXISTS
    (
        select * 
        from  OrderActivationCrossRef
        Where Orderdetails.productId=OrderActivationCrossRef.productId
    )
)

是否可以改进此查询以及LINQ的等效内容?
先感谢您。

2 个答案:

答案 0 :(得分:1)

确切的变量名称将取决于您的上下文的设置方式,但您的整体LINQ查询应该是这样的:

from o in ctx.Orders 
from c in o.Customers
where !o.Activations.Any() &&
    o.Orderdetails.Any(d => d.OrderActivationCrossRef.Any())
select new {o.CustomerId, o.OrderId}

答案 1 :(得分:0)

这是sql

Select O.CustomerId, O.OrderId
from Orders O 
    inner join Customers C on O.CustomerId=C.Customerid -- forces items that exist in customers
    left join activations a on a.orderid = O.orderid
    join orderdetails d on d.orderid = O.orderid  -- forces only items that exist in details
    join OrderActivationCrossRef c on d.productId = c.productId  -- forces only items that exist in crossref
where 
  a.orderid is null -- forces items that don't exist in activations