日期:2014-05-18 浏览次数:20495 次
SELECT A.id,A.name,B.id,B.name,B.版本,B.创建日期 FROM 表A AS A LEFT JOIN 表C AS C ON A.id = C.id1 LEFT JOIN 表B AS B ON B.id = C.id2
------解决方案--------------------
--> 测试数据:[工作] IF OBJECT_ID('[工作]') IS NOT NULL DROP TABLE [工作] GO CREATE TABLE [工作]([id] INT,[name] VARCHAR(5)) INSERT [工作] SELECT 1,'工作A' UNION ALL SELECT 2,'工作B' UNION ALL SELECT 3,'工作C' GO --> 测试数据:[文档] IF OBJECT_ID('[文档]') IS NOT NULL DROP TABLE [文档] GO CREATE TABLE [文档]([id] INT,[name] VARCHAR(5),[版本] VARCHAR(2),[创建日期] DATETIME) INSERT [文档] SELECT 1,'文档A','A1','2012-7-20' UNION ALL SELECT 2,'文档A','A2','2012-7-21' UNION ALL SELECT 3,'文档A','A3','2012-7-21' UNION ALL SELECT 4,'文档B','B1','2012-7-21' GO --> 测试语句: --> 测试数据:[中间表] IF OBJECT_ID('[中间表]') IS NOT NULL DROP TABLE [中间表] GO CREATE TABLE [中间表]([id] INT,[id1] INT,[id2] INT) INSERT [中间表] SELECT 1,1,1 UNION ALL SELECT 2,1,2 UNION ALL SELECT 3,1,3 UNION ALL SELECT 4,2,4 GO --> 测试语句: SELECT * FROM [工作] a left join [中间表] b on a.[id]=b.[id1] left join [文档] c on b.[id2]=c.[id] where not exists(select 1 from [中间表] where [id1]=b.[id1] and [id]>b.[id]) /* id name id id1 id2 id name 版本 创建日期 ----------- ----- ----------- ----------- ----------- ----------- ----- ---- ----------------------- 1 工作A 3 1 3 3 文档A A3 2012-07-21 00:00:00.000 2 工作B 4 2 4 4 文档B B1 2012-07-21 00:00:00.000 3 工作C NULL NULL NULL NULL NULL NULL NULL (3 行受影响) */