日期:2014-05-17  浏览次数:20330 次

sql 合成一条查询语句
表A

   id    id2
    1    11
    2    22

表B 

    id   id2
     1   11
     3   33


表C

    id2  text1
     11  aaa
     22  bbb
     33  ccc


查询 :给出 id 值 是 3

      先从 A 表 查询 id =3 的 id2 的值  如果 A表里没有 从 B表里查询
       
      查到后 从 C表 查询 text1 的值 

1:      select id2 from A where id = 3 ( 得到 id2 值 如果没有 查询 B 表)

2:       select id2 from B where id = 3 (得到 id2 值)

3:       select text1 from C where id2 = 33


上面几步写成一条if else 查询语句怎么写 ?? 
    
    

------解决方案--------------------
declare @id int
if (select id2 from a where id=3) is null
being
    select @id=id2 from B where id = 3
end
else 
begin
    select @id=id2 from a where id=3
end

select text1 from C where id2 = @id

------解决方案--------------------
declare @id INT 
set id='3'

if exists(select id2 from A where id = @id)
     begin 
          select text1 from C where id2 =(select id2 from A where id = @id)
     end

else 
     begin
           select text1 from C where id2 =(select id2 from B where id = @id)
     end

------解决方案--------------------
Select a.id2,b.id2 From a FULL join b on a.id = b.id  Where b.id =3 or a.id =3