有一个表A结构和数据id   type   lid
1     1     1
2     1     2
3     2     1
表B结构和数据id   name
1    AAA
2    BBB
表C结构和数据id  name
1   ccc
我想根据表A的TYPE值来判断,当TYPE=1的时候就和表B INNER JOIN 取出表A的所有字段和表B的NAME字段
如果TYPE=2的时候就表C INNER JOIN 取出表A的所有字段和表C的NAME字段。。
写一个存储过程也可以,写一个视图也可以

解决方案 »

  1.   


    select a.id,a.type,a.lid,name = case when a.type = '1' then b.name when a.type = '2' then c.name else '' end
    from a left join b on a.id = b.id 
    left join c on a.id = c.id
      

  2.   

    select a.*,b.name 
      from (select * from 表A where type=1) a inner join 表B b on a.id=b.id
    union all
    select a.*,b.name 
      from (select * from 表A where type=2) a inner join 表c b on a.id=c.id
      

  3.   

    select a.*,b.name from 表A a inner join 表B b on a.lid=b.id where a.type=1
    union all
    select a.*,c.name from 表A a inner join 表C c on a.lid=c.id where a.type=2
      

  4.   


    select a.*,b.name from a inner join b on a.lid=b.id and a.type=1
    union all
    select a.*,c.name from a inner join c on a.lid=c.id and c.type=2--或者
    select a.*,isnull(b.name,c.name) as name
    from a 
    left join b on a.lid=b.id and a.type=1
    left join c on a.lid=c.id and c.type=2