这个问题已经在 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 实现吗?