日期:2014-05-18  浏览次数:20611 次

大家帮我看看这个问题
表A
id title
1 好人
2 坏人
3 最好的人
4 最坏的人


表B
ID Class AID
1 A 1
2 B 2
3 A 3


想要的一个结果
A.id title B.ID B.CLASS
1 好人 1 A
2 坏人 NULL NULL
3 最好的人 3 A
4 最坏的人 NULL NULL
1 好人 NULL NULL
2 坏人 2 B
3 最好的人 NULL NULL
4 最坏的人 NULL NULL



------解决方案--------------------
select A.id,A.title,B.ID,B.CLASS
from 表A A left join (select * from 表B where Class= 'A ') B on A.id=B.id
union
select A.id,A.title,B.ID,B.CLASS
from 表A A left join (select * from 表B where Class= 'B ') B on A.id=B.id
------解决方案--------------------
/*** 测试:Limpire ***/

--创建表变量:@A
declare @A table(id int,title varchar(8))
insert @A
select 1, '好人 ' union all
select 2, '坏人 ' union all
select 3, '最好的人 ' union all
select 4, '最坏的人 '
--创建表变量:@B
declare @B table(ID int,Class varchar(1),AID int)
insert @B
select 1, 'A ',1 union all
select 2, 'B ',2 union all
select 3, 'A ',3

select a.*, ID = case b.Class when 'A ' then b.ID else null end, Class = case b.Class when 'A ' then b.Class else null end from @A a left join @B b on a.ID = b.ID
union all
select a.*, ID = case b.Class when 'B ' then b.ID else null end, Class = case b.Class when 'B ' then b.Class else null end from @A a left join @B b on a.ID = b.ID

/*
id title ID CLASS
1 好人 1 A
2 坏人 NULL NULL
3 最好的人 3 A
4 最坏的人 NULL NULL
1 好人 NULL NULL
2 坏人 2 B
3 最好的人 NULL NULL
4 最坏的人 NULL NULL
*/