1

这个问题已经在 SO 上被问过多次,但所有答案都是指 SQL 2005 或更高版本(例如OUTER APPLY),我们仍在使用 SQL 2000(由于公司原因太复杂,无法进入此处!)

我有一张表Things和一张表,Widgets关系为 0 到多:

CREATE TABLE Things ( ThingId INT, ThingName VARCHAR(50) )

CREATE TABLE Widgets ( WidgetId INT, ThingId INT, WidgetName VARCHAR(50) )

INSERT INTO Things VALUES ( 1, 'Thing 1' )

INSERT INTO Things VALUES ( 2, 'Thing 2' )

INSERT INTO Things VALUES ( 3, 'Thing 3' )

INSERT INTO Widgets VALUES ( 1, 2, 'Thing 2 Widget 1' )

INSERT INTO Widgets VALUES ( 2, 2, 'Thing 2 Widget 2' )

INSERT INTO Widgets VALUES ( 3, 3, 'Thing 3 Widget 1' )

标准LEFT OUTER JOIN返回预期的 4 行

SELECT * FROM Things t LEFT OUTER JOIN Widgets w ON t.ThingId = w.ThingId

 ThingId | ThingName | WidgetId | ThingId | WidgetName       
---------+-----------+----------+---------+------------------
 1       | Thing 1   | NULL     | NULL    | NULL             
 2       | Thing 2   | 1        | 2       | Thing 2 Widget 1 
 2       | Thing 2   | 2        | 2       | Thing 2 Widget 2 
 3       | Thing 3   | 3        | 3       | Thing 3 Widget 1 

但是,我只想要每个事物的最新小部件,即:

 ThingId | ThingName | WidgetId | ThingId | WidgetName       
---------+-----------+----------+---------+------------------
 1       | Thing 1   | NULL     | NULL    | NULL             
 2       | Thing 2   | 2        | 2       | Thing 2 Widget 2 
 3       | Thing 3   | 3        | 3       | Thing 3 Widget 1 

我的出发点是:

SELECT * FROM Things t LEFT OUTER JOIN (SELECT TOP 1 * FROM Widgets subw WHERE subw.ThingId = t.ThingId ORDER BY subw.WidgetId DESC) w ON t.ThingId = w.ThingId

但这无效,因为父t.ThingId查询中不存在子查询。

这可以使用 SQL 2000 实现吗?

4

1 回答 1

2

如果(ThingId, WidgetId)组合在 table 中是唯一的Widgets,那么这将正常工作:

SELECT t.*, w.* 
FROM 
    dbo.Things AS t 
  LEFT OUTER JOIN 
      ( SELECT ThingId, MAX(WidgetId) AS WidgetId 
        FROM dbo.Widgets 
        GROUP BY ThingId
      ) AS 
    subw
      ON  subw.ThingId = t.ThingId
  LEFT OUTER JOIN
    dbo.Widgets AS w
      ON  w.ThingId = subw.ThingId
      AND w.WidgetId = subw.WidgetId ;
于 2012-11-28T11:23:33.800 回答