简体   繁体   English

SQL 2000 Left Join Top 1 of 0 to many关系

[英]SQL 2000 Left Join Top 1 of 0 to many relationship

This question has been asked multiple times on SO but all the answers refer to SQL 2005 or later (eg OUTER APPLY ) and we are still using SQL 2000 (for corporate reasons too complex to go into here!)这个问题在 SO 上被问过多次,但所有的答案都是指 SQL 2005 或更高版本(例如OUTER APPLY ),我们仍在使用 SQL 2000(由于公司原因太复杂,无法进入这里!)

I have a table of Things and a table of Widgets with a 0 to Many relationship:我有一个Things表和一个具有 0 到多关系的Widgets表:

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' )

A standard LEFT OUTER JOIN returns the expected 4 rows标准的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 

However, I only want the newest Widget for each Thing, ie:但是,我只想要每个事物的最新小部件,即:

 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 

My starting point was:我的出发点是:

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

But this is not valid because the parent t.ThingId does not exist in the sub query.但这无效,因为子查询中不存在父t.ThingId

Can this be achieved using SQL 2000?这可以使用 SQL 2000 实现吗?

If (ThingId, WidgetId) combination is unique in table Widgets , then this will work correctly:如果(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 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM