对如下的3个表查询,SQL语句如何写?表1(Table1): ID Name1
1001 AAA
1002 BBB
..........表2(Table2): ID Name2
2001 中华人民共和国
2002 美利坚合众国
2003 英国
............表3(Table3): ID TableIndex SubID
1 1 1001
2 2 2001
3 2 2003
4 1 1002
............表3的意思是:当TableIndex=1时SubID与表1中的ID对应,当TableIndex=2时SubID与表2中的ID对应。
请问我查询表3时,如何得出下面的结果:
ID Name
1 AAA
2 中华人民共和国
3 英国
4 BBB

解决方案 »

  1.   

    select a.id,
    CASE a.TableIndex WHEN a.TableIndex = 1 THEN (select name1 from table1 where ID = a.subid)
    WHEN a.TableIndex = 2 THEN (select name1 from table2 where ID = a.subid)
    else '表标志位错了啦' end 
    from table3 as a
      

  2.   

    create table table1(id int,name1 varchar(50))
    create table table2(id int,name2 varchar(50))
    create table table3(id int,tableindex int,subid int)
    go
    insert table1 select 1001,'AAA'
    union all select 1002,'BBB'
    insert table2 select 2001,'中华人民共和国'
    union all select 2002,'美利坚合众国'
    union all select 2003,'英国'
    insert table3 select 1,1,1001
    union all select 2,2,2001
    union all select 3,2,2003
    union all select 4,1,1002
    go 
    select * from table1
    select * from table2
    select * from table3select t3.id,case tableindex when 1 then name1 else name2 end as name 
    from table3 t3 left join table1 t1 on t3.subid=t1.id left join table2 t2 on t3.subid=t2.iddrop table table1
    drop table table2
    drop table table3
      

  3.   

    create table t1(ID varchar(10),Name1 varchar(20))
    create table t2(ID varchar(10),Name2 varchar(20))
    create table t3(ID varchar(10),TableIndex int,SubID varchar(10))insert t1 select '1001','AAA'
    union all select '1002','BBB'insert t2 select '2001','中华人民共和国'
    union all select '2002','美利坚合众国'
    union all select '2003','英国'insert t3 select 1,1,'1001'
    union all select 2,2,'2001'
    union all select 3,2,'2003'
    union all select 4,1,'1002'select t3.ID,Name=max(case when TableIndex=1 and SubID=t1.ID then t1.Name1
    when TableIndex=2 and SubID=t2.ID then t2.Name2 end)
    from t1,t2,t3
    group by t3.IDID         Name                 
    ---------- -------------------- 
    1          AAA
    2          中华人民共和国
    3          英国
    4          BBB(所影响的行数为 4 行)警告: 聚合或其它 SET 操作消除了空值。
      

  4.   


    select A.ID,B.Name1 from 表3 A LEFT JOIN 表1 B ON A.SubID=B.ID
    WHERE A.TableIndex=1
    UNION
    SELECT A.ID,B.Name2 from 表3 A left join 表2 B ON A.SubID=B.ID
    WHERE A.TableIndex=2
    ORDER BY A.ID
      

  5.   

    借三楼的数据select b.id,a.name1 from table3 b,table1 a where b.subid=a.id and b.tableindex=1
    union
    select b.id,a.name2 from table3 b,table2 a where b.subid=a.id and b.tableindex=2
    order by b.id