0

我正在尝试根据该记录的最新状态从订单表中选择一组记录。状态保存在另一个名为 orderStatus 的表中。我的表更复杂,但这是一个基本示例

表 - 订单:

orderID

表 - 订单状态:

 orderStatusID
 orderID
 orderStatusCode
 dateTime

一个订单可以有许多状态记录,我只是想获取具有我正在查询的最新状态代码的订单。问题是我得到了很多重复。这是一个基本的例子。

select orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'

我尝试进行内部查询以从按日期时间排序的 orderStatus 表中选择前 1 个。但我仍然看到同样的重复。有人可以为我指出正确的方向吗?

编辑:SQL 服务器 2008

4

5 回答 5

2

一个简单LEFT JOIN的检查订单上没有更新的状态就可以了;

SELECT o.* 
FROM orders o
JOIN orderStatus os
  ON o.orderID = os.orderID
LEFT JOIN orderStatus os2
  ON o.orderID = os2.orderID 
 AND os.dateTime < os2.dateTime
WHERE os.orderStatusCode = 'PENDING' AND os2.dateTime IS NULL;
于 2013-08-29T16:07:45.370 回答
0
select DISTINCT orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'

作为替代方案,您可以 GROUP BY

select orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'
GROUP BY orders.orderID
于 2013-08-29T15:55:36.377 回答
0
select Distinct orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'
于 2013-08-29T15:55:57.437 回答
0

尝试使用这样的子选择:

Select
    o.*
FROM
    Order o inner join OrderStatus os on o.order_id = os.order_id
Where
    os.orderstatus_id in (SELECT max([orderstatus_id]) FROM [OrderStatus]  group by [order_id])
    And os.staus = 'pending'
于 2013-08-29T15:59:42.833 回答
0

尝试日期时间的子查询?

 select orders.orderID
 from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
 where  orderStatusCode = 'PENDING' AND (dateTime)=((SELECT MAX(dateTime) From orders 
 as orders2 Where orders= orders2))
于 2013-08-29T16:02:19.737 回答