1

如何获得下表中同时具有 Feature1 和 Feature2 的汽车和功能(宝马和丰田)?

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

谢谢,基兰

4

3 回答 3

2
select Car
from your_table
where feature in ('f1', 'f2')
group by car
having count(distinct feature) >= 2
于 2012-07-30T14:11:46.757 回答
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;
于 2012-07-30T14:12:16.767 回答
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
于 2012-07-30T14:10:10.870 回答