和IN子句这样的多个值

时间:2012-07-30 14:07:19

标签: sql in-clause

如何获得同时具有Feature1和amp; 1的汽车和功能?下表中的特征2(宝马和丰田)?

Select Car,Feature 
    from Table 
    where Feature in ('Feature1','Feature2') 

提供所有3辆车,包括仅拥有Feature1的本田。这只是实际查询的简化示例,它可以在IN子句中包含数百个值。

Car    Feature
-----  --------
BMW    Feature1
BMW    Feature2
BMW    Feature3
Toyota Feature1
Toyota Feature2
Honda  Feature1

谢谢, 基兰

3 个答案:

答案 0 :(得分:2)

select Car
from your_table
where feature in ('f1', 'f2')
group by car
having count(distinct feature) >= 2

答案 1 :(得分:2)

使用GROUP / HAVING构造,其中HAVING测试IN子句中元素的数量。这样就可以保证两种功能都存在。

SELECT cf.Car
    FROM CarFeature cf
    WHERE cf.Feature IN ('Feature1', 'Feature2')
    GROUP BY cf.Car
    HAVING COUNT(DISTINCT cf.Feature) = 2;

答案 2 :(得分:0)

IN子句实际上是嵌套的OR。以下将为您提供具有这两种功能的所有汽车。

SELECT U.Car FROM
  (
   Select Car from Table where Feature ='Feature1'
   UNION ALL
   Select Car from Table where Feature ='Feature2'
  ) AS U
WHERE COUNT(U.Car) > 1