我的数据库存储在 sql server 2005 db 中。
此查询执行时间不到一秒:
SELECT * FROM (
SELECT ROW_NUMBER() OVER ( ORDER BY tblOrders.orderid ) AS RowNum,
SUM(tblProducts.Price) as price
FROM tblOrders
LEFT OUTER JOIN tblOrderDetails ON tblOrders.orderid = tblOrderDetails.OrderId
LEFT OUTER JOIN tblProducts ON tblOrderDetails.ProductId = tblProducts.ProductId
GROUP BY tblOrders.orderid
) as x
where RowNum >= 21001 and RowNum < 21011
虽然此查询需要 10 秒才能执行:
SELECT * FROM (
SELECT ROW_NUMBER() OVER ( ORDER BY tblOrders.orderid ) AS RowNum,
SUM(tblProducts.Price) as price,
OrderDate
FROM tblOrders
LEFT OUTER JOIN tblOrderDetails ON tblOrders.orderid = tblOrderDetails.OrderId
LEFT OUTER JOIN tblProducts ON tblOrderDetails.ProductId = tblProducts.ProductId
GROUP BY tblOrders.orderid, tblOrders.OrderDate
) as x
where RowNum >= 21001 and RowNum < 21011
为什么会有这样的差异?
所有表都有一个名为 id 的列,其中包含主键。不知道为什么 orderid 和 ProductId 也存在,因为我没有设计数据库。
/巴里
更新
OrderDate 是日期时间
第二次更新
请记住,三个表都有一个 id 列作为主键。但是,在表之间引用时会使用 orderid、productid 等。我不确定为什么要以这种方式实施,但我猜它非常错误。
tblOrders:
Id; int; no null; PK
OrderId; int; allow null
OrderDate; datetime; allow null
tblOrderDetails:
Id; int; no null; PK
OrderId; int; allow null
ProductId; int; allow null
tblProducts:
Id; int; PK; no null
ProductId; allow null
Price; money; allow null
这是一个足够的查询执行计划吗? -
第三次更新
这只需一秒钟即可执行 -
SELECT ROW_NUMBER() OVER ( ORDER BY tblOrders.orderid ) AS RowNum,
SUM(tblProducts.Price) as price,
OrderDate
FROM tblOrders
LEFT OUTER JOIN tblOrderDetails ON tblOrders.orderid = tblOrderDetails.OrderId
LEFT OUTER JOIN tblProducts ON tblOrderDetails.ProductId = tblProducts.ProductId
GROUP BY tblOrders.orderid, OrderDate
而这只有 2 秒 -
SELECT * FROM (
SELECT ROW_NUMBER() OVER ( ORDER BY tblOrders.orderid ) AS RowNum,
SUM(tblProducts.Price) as price,
MAX(tblOrders.OrderDate) as OrderDate -- do this instead of grouping
FROM tblOrders
LEFT OUTER JOIN tblOrderDetails ON tblOrders.orderid = tblOrderDetails.OrderId
LEFT OUTER JOIN tblProducts ON tblOrderDetails.ProductId = tblProducts.ProductId
GROUP BY tblOrders.orderid ) as x
但这需要10秒——
SELECT * FROM (
SELECT ROW_NUMBER() OVER ( ORDER BY tblOrders.orderid ) AS RowNum,
SUM(tblProducts.Price) as price,
MAX(tblOrders.OrderDate) as OrderDate -- do this instead of grouping
FROM tblOrders
LEFT OUTER JOIN tblOrderDetails ON tblOrders.orderid = tblOrderDetails.OrderId
LEFT OUTER JOIN tblProducts ON tblOrderDetails.ProductId = tblProducts.ProductId
GROUP BY tblOrders.orderid ) as x
where RowNum >= 21001 and RowNum < 21011
where 子句增加了 8 秒。为什么?