比如a表中有字段type,type中内容为1或2,我想在type为1的时候连接b表,type为2的时候连接c表,有办法用一条语句实现么?

解决方案 »

  1.   

    select * from ta a left join  b on  a.id=b.id and a.type=1
    union all
    select * from ta a left join  c on  a.id=c.id and a.type=2
      

  2.   

    select * 
    from a  left join  b  on ....
    where a.type=1
    union all
    select * 
    from a  left join  c  on ....
    where a.type=2
      

  3.   


    select a.id, isnull(b.c1,c.c1),isnull(b.c2,c.c2),....
    from ta a left join tb b on a.id = b.id and a.type = 1
              left join tc c on a.id = c.id and a.type = 2
      

  4.   

    select * 
    from a 
    left inner join b 
    on a.type=1 and 连接条件 
    union all
    select * 
    from a 
    left inner join c 
    on  a.type=2 and 连接条件
      

  5.   

    不好意思,union我是知道的,我是想不用union all的话,还有其他方法么?  3楼的不行,我之前试过了
      

  6.   

    刚又试了一下,这个好像可以,我之前用的是inner join,我再想一下,对了,就给分
      

  7.   

    最好上点数据说明一下,我的理解是要用到动态SQL
      

  8.   

    --创建环境
    create table ta
    (
    id int,
    type int
    )create table tb
    (
    id int,
    name varchar(10)
    )create table tc
    (
    id int,
    name varchar(10)
    )insert into ta select 1,1
    insert into ta select 2,1
    insert into ta select 3,2
    insert into ta select 4,2insert into tb select 1,'张三'
    insert into tb select 2,'李四'
    insert into tc select 3,'王二麻子'
    insert into tc select 4,'冷箫轻笛'--查询
    select a.id,case a.type when 1 then b.name when 2 then c.name end as name
    from ta a left join tb b on a.id = b.id and a.type = 1
              left join tc c on a.id = c.id and a.type = 2--结果
    /*
    id          name
    ----------- ----------
    1           张三
    2           李四
    3           王二麻子
    4           冷箫轻笛(4 行受影响)*/--删除环境
    drop table ta
    drop table tb
    drop table tc
      

  9.   


    --查询
    select a.id,isnull(b.name,c.name) as name
    from ta a left join tb b on a.id = b.id and a.type = 1
              left join tc c on a.id = c.id and a.type = 2
    /*
    id          name
    ----------- ----------
    1           张三
    2           李四
    3           王二麻子
    4           冷箫轻笛(4 行受影响)*/
      

  10.   

    您之前说的对了,是left而不是inner,不过我还没转过弯了,给分先