id f_id name
1    1   A
2    1   B
3    2   B
4    2   C 
5    3   C
6    4   C
7    5   A
8    5   B
9    5   C
10    5   D
11    6   A
12    6   B如何查询该表里面name为'A'和'B',取得对应f_id为1和6的记录

解决方案 »

  1.   

    --> 测试数据:[TB]
    if object_id('[TB]') is not null drop table [TB]
    create table [TB]([id] int,[f_id] int,[name] varchar(1))
    insert [TB]
    select 1,1,'A' union all
    select 2,1,'B' union all
    select 3,2,'B' union all
    select 4,2,'C' union all
    select 5,3,'C' union all
    select 6,4,'C' union all
    select 7,5,'A' union all
    select 8,5,'B' union all
    select 9,5,'C' union all
    select 10,5,'D' union all
    select 11,6,'A' union all
    select 12,6,'B'select * from [TB] WHERE NAME IN ('A','B') AND f_id IN(1,6)/*
    id          f_id        name
    ----------- ----------- ----
    1           1           A
    2           1           B
    11          6           A
    12          6           B(4 行受影响)
    */
      

  2.   

    select f_id from
    (
    select distinct f_id from tb where name = 'A'
    union all
    select distinct f_id from tb where name = 'B'
    ) t
    group by f_id having count(1) = 2
      

  3.   

    select
      *
    from
      tb t
    where
      exists(select 1 from tb where name in('a','b') and f_id in('1','6'))
      

  4.   

    select * from tb where (name='A' or name='B') and (f_id=1 or f_id=6)
      

  5.   


    --sql2005
    create table [TB]([id] int,[f_id] int,[name] varchar(1))
    insert [TB]
    select 1,1,'A' union all
    select 2,1,'B' union all
    select 3,2,'B' union all
    select 4,2,'C' union all
    select 5,3,'C' union all
    select 6,4,'C' union all
    select 7,5,'A' union all
    select 8,5,'B' union all
    select 9,5,'C' union all
    select 10,5,'D' union all
    select 11,6,'A' union all
    select 12,6,'B'
    goselect distinct f_id
    from tb t
    where stuff((select ',' + [name] from tb where f_id = t.f_id for xml path('')),1,1,'') = 'A,B'drop table tb
    /*f_id
    -----------
    1
    6
      

  6.   


    不过这里有个小问题,如果我的入参不按'A,B'而是'B,A'排列就不行了不知道其他兄弟是否有另外的语句处理的
      

  7.   


    create table [TB]([id] int,[f_id] int,[name] varchar(1))
    insert [TB]
    select 1,1,'A' union all
    select 2,1,'B' union all
    select 3,2,'B' union all
    select 4,2,'C' union all
    select 5,3,'C' union all
    select 6,4,'C' union all
    select 7,5,'A' union all
    select 8,5,'B' union all
    select 9,5,'C' union all
    select 10,5,'D' union all
    select 11,6,'A' union all
    select 12,6,'B'
    gowith cte as
    (
    select f_id from tb where [name] = 'A'
    union all
    select f_id from tb where [name] = 'B'
    ),ct1 as
    (
    select f_id
    from cte
    group by f_id
    having count(*) = 2
    )select f_id
    from tb
    where f_id in (select f_id from ct1)
    group by f_id
    having count(*) = 2drop table tb/*
    f_id
    -----------
    1
    6(2 行受影响)