表:basic 字段有 id,nick(存放的是某个用户的基本资料,包括nick昵称)
表:top   字段有 topID,id1,id2(配对表,id1和id2代表的是二个人,取自basic的id字段)如果有一要求,显示top表里面二个人的昵称应该怎么写SQL?
也就是,
id1对应basic.id 
id2对应basic.id
取出id1和id2这二个人的昵称nick

解决方案 »

  1.   

    select a.topID,b.nick,c.nick
    from top as a
    left join basic as b on a.id1 = b.id
    left join basic as c on a.id2 = b.id
      

  2.   

    抱歉,更正一下:
    select a.topID,b.nick,c.nick
    from top as a
    left join basic as b on a.id1 = b.id
    left join basic as c on a.id2 = c.id
      

  3.   

    select a.*,b.*  from top  a inner join basic  b on (a.id1=b.id or a.id2=b.id)
      

  4.   

    declare @basic table(id int,nick char(10))
    insert @basic
    select 1, 'haha'       union all
    select 2,  'hoho'       union all
    select 3,  'hehe'    
       
    declare @top table(topid int,id1 char, id2 char)
    insert @top
    select 1,  1   ,2     union all
    select 2,  1 , 3   
    select * from @top
    select topid,b.nick,c.nick from @top , @basic as b ,@basic as c where id1=b.id and id2=c.id 
    ----------------------结果
    1 haha       hoho      
    2 haha       hehe    
    ------------------------------