select a.id1,a.value1,b.id2,b.value2
from tb1 a right join tb2 b on a.id1=b.id2

解决方案 »

  1.   

    --上面写错对应关系,改一下:select a.id1,a.value1,b.id2,b.value2
    from tb1 a right join tb2 b on a.id2=b.id2
      

  2.   

    --测试--测试数据
    create table tb1(id1 int,value1 int,id2 int)
    insert tb1 select 1,77,3create table tb2(id2 int,value2 varchar(10))
    insert tb2 select 1,'福建'
    union  all select 2,'广东'
    union  all select 3,'广西'
    union  all select 4,'湖南'
    go--查询
    select a.id1,a.value1,b.id2,b.value2
    from tb1 a right join tb2 b on a.id2=b.id2
    order by case when a.id1 is null then 1 else 0 end,b.id2  --这里加了排序
    go--删除测试
    drop table tb1,tb2/*--测试结果
    ----------- ----------- ----------- ---------- 
    1           77          3           广西
    NULL        NULL        1           福建
    NULL        NULL        2           广东
    NULL        NULL        4           湖南(所影响的行数为 4 行)
    --*/
      

  3.   

    实际表tb1和tb2中还有两个限制条件,如下
    tb1表:
    ----------
    id1    value1     id2   exp1
    1       77         3      6
    tb2表:
    -------------
    id2    value2     exp2
    1       福建        4
    2       广东        4
    3       广西        4
    4       湖南        4
    要求:取出如下数据:
    -----------------------
    id1     value1    id2     value2
    1        77        3       广西
    null     null      1       福建
    null     null      2       广东
    null     null      4       湖南
    我写的是
    select a.id1,a.value1,b.id2,b.value2
    from tb1 a right join tb2 b on a.id1=b.id2
    where (a.exp1=6 or a.exp is null ) and b.exp2=4
    应该是这样写,可是为什么取出来的数据没把tb2取全呢???
      

  4.   

    --测试--测试数据
    create table tb1(id1 int,value1 int,id2 int,exp1 int)
    insert tb1 select 1,77,3,6create table tb2(id2 int,value2 varchar(10),exp2 int)
    insert tb2 select 1,'福建',4
    union  all select 2,'广东',4
    union  all select 3,'广西',4
    union  all select 4,'湖南',4
    go--查询
    select a.id1,a.value1,b.id2,b.value2
    from tb1 a right join tb2 b on a.id1=b.id2
    where (a.exp1=6 or a.exp1 is null ) and b.exp2=4go--删除测试
    drop table tb1,tb2/*--测试结果
    id1         value1      id2         value2     
    ----------- ----------- ----------- ---------- 
    1           77          1           福建
    NULL        NULL        2           广东
    NULL        NULL        3           广西
    NULL        NULL        4           湖南(所影响的行数为 4 行)
    --*/
      

  5.   

    不会啊,你看我上面的测试,一样是取全了的.当然,这句中的a.exp这个是笔误吧?
    where (a.exp1=6 or a.exp is null ) and b.exp2=4
      

  6.   

    你先不要这个条件:--where (a.exp1=6 or a.exp is null ) and b.exp2=4看看查询结果是否正确,如果不正确,就不关条件的事
    如果正确,你再看看,按这个条件为什么有的数据不出来.
      

  7.   

    试一下:
    select a.id1,a.value1,b.id2,b.value2
    from tb1 a right join tb2 b on a.id1=b.id2
    where (a.exp1=6 or a.exp is null or a.exp='') and b.exp2=4