2

我有 2 张桌子

Delivery
--------
deliveryid int (PK)

description long varchar

DeliveryHistory
---------------
historyid int

delievryid int

statusid int

recordtime timestamp

我正在尝试做的是左外连接,以从表 Delivery 中带回所有记录,每次交付时只有 DeliveryHistory 中的最新条目。但是,如果 DeliveryHistory 中没有用于交付的条目,我想要一个空值

我已经这样做了:

select d.deliveryid,d.description, h.statusid from delivery d
left outer join  Deliveryhistory h on d.deliveryid = h.deliveryid
where  h.recordtime =
       ( SELECT MAX(recordtime)
           FROM Deliveryhistory
          WHERE deliveryid = d.deliveryid)

但它只返回在 DeliveryHistory 中有条目的行。

4

4 回答 4

2

您的 where 子句导致所有空值都被排除在外。尝试

where  h.RecordTime is null OR
       h.recordtime =
       ( SELECT MAX(recordtime)
           FROM Deliveryhistory
          WHERE deliveryid = d.deliveryid)
于 2012-08-01T17:31:14.343 回答
1
select d.deliveryid,d.description, h.statusid from delivery d
left outer join  Deliveryhistory h on d.deliveryid = h.deliveryid
where  (h.recordtime =
   ( SELECT MAX(recordtime)
       FROM Deliveryhistory
      WHERE deliveryid = d.deliveryid)
  or h.deliveryid = null)
于 2012-08-01T17:31:08.050 回答
0

现有的答案就是全部,但如果您想在不使用WHERE子句的情况下执行此操作,则可以使用以下构造。

SELECT  d.deliveryid
        ,d.description
        , dh.statusid
FROM    Delivery d 
        LEFT OUTER JOIN (
          SELECT deliveryid, MAX(recordtime) AS recordtime
          FROM   DeliveryHistory
          GROUP BY
                 deliveryid
        ) dhm ON dhm.deliveryid = d.deliveryid                 
        LEFT OUTER JOIN DeliveryHistory dh ON dh.deliveryid = dhm.deliveryid 
                                              AND dh.recordtime = dhm.recordtime
于 2012-08-01T17:35:38.833 回答
0

CTE 产生 maxrow(IFF 实现支持 CTE ;-) 加上与 CTE 的简单左连接。

WITH last AS (
        SELECT * FROM Deliveryhistory dh
        WHERE NOT EXISTS (
                SELECT * 
                FROM Deliveryhistory nx
                WHERE nx.deliveryid = dh.deliveryid
                AND nx.recordtime > dh.recordtime -- no one is bigger: dh must be the max
                )
        )
SELECT d.deliveryid, d.description, l.statusid 
FROM delivery d
LEFT JOIN last l ON d.deliveryid = l.deliveryid
        ;
于 2012-08-01T17:46:12.307 回答