日期:2014-05-16  浏览次数:20583 次

求一句Select查询语句
现在有表A中字段XXX,XXX的值可能为空,也可能是表B中的YYY字段的值,也可能是表C中ZZZ字段的值,YYY和ZZZ的值都不重复,表B和表C有一些相同名字的字段。像下面这样:

表A XXX A1 A2 A3
表B YYY MM NN
表C ZZZ MM NN

现在我想把表A中的项全部列出来,如果XXX能和表B中的YYY对上,那么同时列出表B中的MM NN,如果XXX能和表C中的ZZZ对上,那么同时列出表C中的MM NN

XXX A1 A2 A3 MM NN

请问要实现这个,Select语句该怎么写?
------解决方案--------------------
select * from a
left outer join b.yyy=a.xxx
left outer join c.zzz=a.xxx
------解决方案--------------------
B,C表inner join,再跟A表做left join,然后A的XXX is not null
------解决方案--------------------

select a.XXX,a.A1,a.A2,a.A3,
       case when b.YYY is not null then b.MM
            when c.ZZZ is not null then c.MM
            else null end 'MM',
       case when b.YYY is not null then b.NN
            when c.ZZZ is not null then c.NN
            else null end 'NN'
 from 表A a
 left join 表B b on a.XXX=b.YYY
 left join 表C c on a.XXX=c.ZZZ

------解决方案--------------------
A,B连接查询   union all  A,C连接查询
------解决方案--------------------

select XXX,A1,A2,A3, MM = case when A.XXX = B.YYY then B.MM when A.XXX = C.ZZZ then C.MM end,
NN = case when A.XXX = B.YYY then B.NN when A.XXX = C.ZZZ then C.NN end
from A left join B on A.XXX = B.YYY left join C on A.XXX = C.ZZZ