表结构大致如下:
Table_A:
A_id   A_content A_others
1       xxx      ……
2       xxx      ……
3       xxx      ……
4       xxx      ……
Table_B:
B_id  B_content  B_others  A_ids
1      ……         ……      1,2
2      ……         ……      1,2,3
3      ……         ……      2,3
也就是说Table_B中的A_ids存放的是Table_A的ID
怎样查询出A_ids对应Table_A的记录?
select * from Table_A A where A.A_id in(1,2,3)
select B.A_ids from Table_B B where B.B_id = 2 --输出为:1,2,3select * from Table_A A where A.A_id in(select B.A_ids from Table_B B where B.B_id)
这样写是不行的!奇怪!

解决方案 »

  1.   

    declare @t table(ID int,name varchar(10))
    insert @t select 1,'A'
    insert @t select 2,'B'
    declare @s table(ID int,name varchar(10))
    insert @s select 1,'A'
    insert @s select 2,'B'
    insert @s select 1,'B'
    select * from @t t where t.ID in(select s.ID from @s s where s.name='B') 
    ID          name
    ----------- ----------
    1           A
    2           B
      

  2.   

    select * from Table_A A where charindex(','+cast(A.A_id as varchar)+',',','+(select B.A_ids from Table_B B where B.B_id=2)+',')>0 
      

  3.   


    declare @t1 table(id int identity(1,1),name char(1))
    declare @t2 table(id int identity(1,1),name char(2),a_id varchar(20))
    insert @t1 select 'a'
    union all select 'b'
    union all select 'c'
    union all select 'd'
    union all select 'e'insert @t2 select 'aa','1,2'
    union all select 'bb','1,2,3'
    union all select 'cc','2,3'
    union all select 'cc','3,4'select * from @t1
    select * from @t2
    select distinct
    a.*
    from @t1 a,@t2 b
    where charindex(convert(varchar(10),a.id),b.a_id) > 0
    /**
    1 a
    2 b
    3 c
    4 d
    **/
      

  4.   

    楼上的可能意思理解错了Table_B中有一个字段的内容存放的是Table_A的多条id,以逗号来分隔格式为 1,2,3
      

  5.   

    能不能解释以下charindex的时候 总是要在字符串两边加2个逗号
      

  6.   

    楼主你的想法很好,但是,子查询返回的是一个值,并非是一个集合,所以你用 in 操作是不行的,可以用动态查询实现:
    declare @sql nvarchar(4000)
    select @sql=isnull(@sql,'') + N'select * from Table_A where A_id in (' + max(A_ids) + ')'
    from  Table_B
    group by A_ids
    exec (@sql)就可以了,哈哈.