SQL Server CE - bad performance

本文关键字:bad performance CE Server SQL | 更新日期: 2023-09-27 18:09:58

我正在开发一个使用SQL Server CE数据库的应用程序,我对查询的性能有问题。例如,一个获取客户最后订单的简单查询:

SELECT 
    Customer.Name, Orders.Amount AS LastOrderAmount
FROM   
    Customers
LEFT JOIN 
    Orders ON Orders.OrderId IN (SELECT TOP(1) OrderId
                                 FROM Orders 
                                 WHERE CustomerId = Customer.CustomerId 
                                 ORDER BY OrderNum DESC)

这个查询非常慢。只有30个客户和大约300个订单,几乎需要10秒才能完成!

我使用SqlCEDataAdapter查询。我也尝试使用SqlCeResultSet,但差异可以忽略不计。此外,我有一个关于Orders.CustomerId的索引(创建它并没有太大的区别,尽管)。

现在,我不期待从SQL Server CE的奇迹,但这只是可怕的。所以,我能做些什么来提高性能,还是它就是那么慢?

SQL Server CE - bad performance

试试这个:

SELECT cus.Name
     , outerOrd.Amount AS LastOrderAmount
  FROM Customers cus
  LEFT JOIN Orders outerOrd on outerOrd.CustomerId = cus.CustomerId
 WHERE not exists (SELECT *
                     FROM Orders innerOrd
                    WHERE innerOrd.CustomerId = cus.CustomerId
                      and innerOrd.OrderId > outerOrd.OrderId 
                  )

编辑完毕,可能这样更好:

SELECT cus.Name
     , ord.Amount AS LastOrderAmount
  FROM Customers cus
  LEFT JOIN Orders ord on ord.CustomerId = cus.CustomerId
 WHERE ord.OrderId = (SELECT max(OrderId)
                        FROM Orders
                       WHERE CustomerId = cus.CustomerId
                     )