SQL - 使这个语句更快,即持续时间更短,读取

时间:2010-09-17 16:27:00

标签: linq-to-sql sql

鉴于以下表格:

Orders (OrderID, OrderStatus, OrderNumber) 
OrderItems(OrderItemID, OrderID, ItemID, OrderItemStatus)

订单:2537条记录 订单商品:1319条记录

我在

上创建了索引
  1. 订单(OrderStatus)
  2. 的OrderItems(订单ID)
  3. 的OrderItems(OrderItemStatus)
  4. 我有以下SQL语句(由LinqToSql生成),在执行时,它具有:   - 持续时间= 8789   - 读= 7809.

    exec sp_executesql N'SELECT COUNT(*) AS [value]
    FROM [dbo].[Orders] AS [t0]
    WHERE ([t0].[OrderStatus] = @p0) OR (EXISTS(
        SELECT NULL AS [EMPTY]
        FROM [dbo].[OrderItems] AS [t1]
        WHERE ([t1].[OrderID] = [t0].[OrderID]) AND ([t1].[OrderItemStatus] = @p1)
        ))',N'@p0 nvarchar(2),@p1 nvarchar(2)',@p0=N'KE',@p1=N'KE'
    

    我能做些什么来加快速度吗?

3 个答案:

答案 0 :(得分:1)

如果表中的列是varchars

,则使所有这些nvarchars参数变量
))',N'@p0 varchar(2),@p1 varchar(2)',@p0=N'KE',@p1=N'KE'

另见:sp_executesql causing my query to be very slow

答案 1 :(得分:0)

依靠单个索引而不是*

答案 2 :(得分:0)

这可能会产生更好的sql。

IQueryable<int> query1 =
  from oi in db.OrderItems
  where oi.OrderItemStatus == theItemStatus
  select oi.OrderID;

IQueryable<int> query2 =
  from o in db.Orders
  where o.OrderStatus == theOrderStatus
  select o.OrderID;

IQueryable<int> query3 = query1.Concat(query2).Distinct();

int result = query3.Count();