有一数据表A,结构如下
ID       RID
1        1
1        2
1        3
1        4
2        1
2        3
2        4
3        1
3        4
4        1
4        2
4        3
4        4问题是:我如何取出RID即等于1又等于3的不重复ID?即结果是:1,2,4
除了用intersect这个,还有其他方法吗?

解决方案 »

  1.   

    select distinct id from A t where RID=1
     and exists(select 1 from A where id=t.id and RID=3)
      

  2.   

    感谢ssp2009的回复,你这样做是没有问题,可是如果我要查找RID=1并且RID=2并且RID=3并且RID=4还有很多条件,岂不是要写好长的SQL语句?有没有更简单的办法?
      

  3.   

    多写几个and了,没有别的办法了。
      

  4.   

    if not object_id('tb') is null
    drop table tb
    Go
    Create table tb([ID] int,[RID] int)
    Insert tb
    select 1,1 union all
    select 1,2 union all
    select 1,3 union all
    select 1,4 union all
    select 2,1 union all
    select 2,3 union all
    select 2,4 union all
    select 3,1 union all
    select 3,4 union all
    select 4,1 union all
    select 4,2 union all
    select 4,3 union all
    select 4,4
    GO
    SELECT  ID
    FROM    ( SELECT    *
              FROM      dbo.tb PIVOT( COUNT(RID) FOR rid IN ( [1], [3] ) )AS p
            ) AS T
    WHERE   [1] = 1
            AND [3] = 1
      

  5.   

    还可以用JOIN的写法,不过更麻烦
      

  6.   

    select id from 
    (select id,
           RID=(select ''+rtrim(id) from A where id=t.id)
    from A t group by id) t 
    where patindex('%[^1234]%',rid)=0
      

  7.   

    select
       id
    from
       tb
    where
       RID in(1,3)
    and
       ID in(select ID from tb group by ID having COUNT(1)>2)
    group  by
       ID
      

  8.   

    借楼上测试数据一用
    if not object_id('tb') is null
        drop table tb
    Go
    Create table tb([ID] int,[RID] int)
    Insert tb
    select 1,1 union all
    select 1,2 union all
    select 1,3 union all
    select 1,4 union all
    select 2,1 union all
    select 2,3 union all
    select 2,4 union all
    select 3,1 union all
    select 3,4 union all
    select 4,1 union all
    select 4,2 union all
    select 4,3 union all
    select 4,4
    GO
    --这个写法适用于RID不重复的情况
    SELECT ID
    FROM TB
    WHERE RID IN (1,3) --写你的条件
    GROUP BY ID HAVING COUNT(1)=2 --有几个数就写几
    /*
    1
    2
    4
    */
      

  9.   

    感谢szstephenzhou的回复,我想请问一下,是我的数据结构不合理造成的吗?
    本意是这样的:这是一张酒店的资料表,酒店的基础信息我存在一张表里,这张表存储的是酒店的配套设施,比如网线,空调,电视等等,和酒店的房间属于一对多的关系,所以我存了分表,先要前台要查询有网线并且有空调的酒店房间!我想问一下,我这样设计的表结构有问题吗?有更好的解决方案吗?
      

  10.   

    如果酒店设施比较固定,可以改成列结构的,比如HAS_WEB,HAS_AIR_CONDITION等。
    如果不固定,也可以试试用枚举值放在一列存储,比如,1,2,这样的,查找的时候用LIKE叠加条件即可。
      

  11.   

    如果酒店设施比较固定,可以改成列结构的,比如HAS_WEB,HAS_AIR_CONDITION等。
    如果不固定,也可以试试用枚举值放在一列存储,比如,1,2,这样的,查找的时候用LIKE叠加条件即可。不是固定的,但如果按照枚举值放在一列存储,就要写很多LIKE,我担心速度会慢,比如:
    select ID from A where RID LIKE '%,1,%' AND RID LIKE '%,2,%' AND RID LIKE '%,3,%' AND RID LIKE '%,4,%'......,速度难以保障