tab1
------------------
id     name
1       a
2       b
3       c
4       d
5       e
tab2
------------------
id       no
1        101
1        102
3        101
4        101
5        101
5        102
5        103如表tab1、tab2,如何通过id关联,取出当no为同时为101、102或同时为101、102、103的name,谢谢!

解决方案 »

  1.   

    select b.id,b.no,a.name from b left join a where
     a.id=b.id 
      

  2.   


    declare @tab1 table (id int,name varchar(1))
    insert into @tab1
    select 1,'a' union all
    select 2,'b' union all
    select 3,'c' union all
    select 4,'d' union all
    select 5,'e'declare @tab2 table (id int,no int)
    insert into @tab2
    select 1,101 union all
    select 1,102 union all
    select 3,101 union all
    select 4,101 union all
    select 5,101 union all
    select 5,102 union all
    select 5,103select no from 
    (
    select a.id as aid,b.id as bid,b.no from @tab1 a right join 
    @tab2 b on a.id=b.id
    )aa 
    group by no having(count(*)>1)
    /*
    no
    -----------
    101
    102
    */
    不知道你想要什么样的结果。
      

  3.   


    select a.id, a.name from tab1 a, tab2 b
    where a.id = b.id and b.name in (101, 102, 103)
      

  4.   


    declare @tab2 table (id int,no int)
    insert into @tab2
    select 1,101 union all
    select 1,102 union all
    select 3,101 union all
    select 4,101 union all
    select 5,101 union all
    select 5,102 union all
    select 5,103select id from( select id, 
    no=stuff((select ','+ltrim(no) from @tab2 t where id=m.id for xml path('')), 1, 1, '') 
    from @tab2 m group by id )aa
    where charindex(',101,102,',','+no+',')>0
    or charindex(',101,102,103,',','+no+',')>0
    /*
    id
    -----------
    1
    5
    */
      

  5.   

    to: shinesky
    谢谢!你的是 or 关系,我希望得到的结果是 and 关系to:maco_wang
    谢谢!其实tab2是tab1的一个属性表,当用户查询时,给定了101、102编号的属性,要取出这两个编号属性同时存在的tab1.name。不知道清楚没有,谢谢。
      

  6.   

    tab2是tab1的属性表,根据数据库完整性约束,tab2中的id都应该是tab1中存在。--如果要判断一下:
    --1、最简单的方式:(效率不好)
    select id from( select id, 
    no=stuff((select ','+ltrim(no) from @tab2 t where id=m.id for xml path('')), 1, 1, '') 
    from @tab2 m group by id )aa
    where (charindex(',101,102,',','+no+',')>0
    or charindex(',101,102,103,',','+no+',')>0)
    and id in(select id from @tab1)--2、提高些效率select id from( select id, 
    no=stuff((select ','+ltrim(no) from @tab2 t where id=m.id for xml path('')), 1, 1, '') 
    from @tab2 m group by id )aa left join @tab1 bb on aa.id=bb.id
    where (charindex(',101,102,',','+aa.no+',')>0
    or charindex(',101,102,103,',','+aa.no+',')>0)
    and bb.id is not null
      

  7.   

    to:maco_wang谢谢你提供的方法。 就不知我到时挂在服务器上性能如何(我是按方法2写的)。先把分结了。