从关系中选择最后一条记录

时间:2013-02-19 15:59:50

标签: sql-server-2008 tsql

我有这种情况。我有一个与Orders相关的表OrderStatus

OrderStatus

id | orderId | created

我需要以最后状态检索Orders。我尝试了这个查询,我不知道它是否具有高性能。我需要知道是否有更好的解决方案。

select Orders.id, OrderStatus.status from Orders
inner join OrderStatus on OrderStatus.id = 
    (select top 1 id from OrderStatus where orderId = Order.id order by created desc)

2 个答案:

答案 0 :(得分:2)

您可以使用Row_Number功能:

WITH CTE AS
(
   SELECT Orders.id, OrderStatus.status,
      RN = ROW_NUMBER() OVER (
                        PARTITION BY OrderStatus.OrderId 
                        ORDER BY created DESC) 
   FROM Orders
   INNER JOIN OrderStatus ON  OrderStatus.OrderId = Orders.id
)
SELECT id, status
FROM CTE WHERE RN = 1

我使用了common-table-expression,因为它可以直接过滤,而且非常易读。

答案 1 :(得分:2)

相关子查询通常是坏消息(有时SQL Server可以对其进行优化,有时它的行为就像一个非常慢的循环)。除非您没有任何主键,否则还不确定为什么您认为只需要获取最新状态时需要DISTINCT ...

;WITH x AS 
(
  SELECT o.id, os.status, 
    rn = ROW_NUMBER() OVER (PARTITION BY os.orderId ORDER BY created DESC)
    FROM dbo.Orders AS o
    INNER JOIN dbo.OrderStatus AS os
    ON o.id = os.orderId
)
SELECT id, status
  FROM x
  WHERE rn = 1;