SQL 2000 Left Join 0到0之间的关系

时间:2012-11-28 11:16:05

标签: sql tsql sql-server-2000

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

我有一张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 

但是,我只想要每个Thing的最新Widget,即:

 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实现吗?

1 个答案:

答案 0 :(得分:2)

如果(ThingId, WidgetId)组合在表格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 ;