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

一个我觉的不可能完成的SQL
表1                                                                   表2
商品1flg                                                       商品1code(3位)
商品2flg                                                       商品2code
商品3flg                                                       商品3code
商品4flg                                                       商品4code
商品5flg                                                       商品5code


目标是将两张表连接起来。
表1的flg是true的话,将表2中同名的字段不为空的找出来。
表1的flg是false的话,将表2中同名的字段不为空的不能找出来。
列子:
表1                                                   表2
1,     1   1   0   0   0                             001,002,       ,     ,                                                          
          0   1   0   0   1                             001,     ,003,       ,
                                                              ,002,003,004

这样的数据的话连接的表只能出现一条记录,就是1号。
这样说大家能明白了吗?

   


   


------解决方案--------------------
select
b.*
from
表1 a,表2 b
where
a.商品1flg=(case b.商品1code is null then 0 else 1 end)
and
a.商品2flg=(case b.商品2code is null then 0 else 1 end)
and
a.商品3flg=(case b.商品3code is null then 0 else 1 end)
and
a.商品4flg=(case b.商品4code is null then 0 else 1 end)
and
a.商品5flg=(case b.商品5code is null then 0 else 1 end)
------解决方案--------------------
declare @t1 table(flag1 int,flag2 int,flag3 int,flag4 int,flag5 int)
insert into @t1 select 1,1,0,0,0
insert into @t1 select 0,1,0,0,1

declare @t2 table(code1 varchar(4),code2 varchar(4),code3 varchar(4),code4 varchar(4),code5 varchar(4))
insert into @t2 select '001 ', '002 ',null ,null ,null
insert into @t2 select '001 ',null , '003 ',null ,null
insert into @t2 select null , '002 ', '