SQL仅在所有指定条件为真的情况下连接表

时间:2011-11-07 01:05:56

标签: mysql sql

假设我有两个表,'汽车'和'属性',由表'car_properties'链接。我可以选择所有说过的车,电动车窗无线电两者,做如下的事情......

SELECT cars.id 
FROM cars 
JOIN car_properties 
   ON cars.id = car_properties.car_id 
WHERE 
   car_properties.property_id = 1 
   OR car_properties.property_id = 2

其中'electric windows'的property_id为'1','car radio'为'2'。

但是,我真正想要做的只是选择具有两种属性的汽车(不只是一种或两种或两种)。

我怀疑这很简单,但最有效的方法是什么?

1 个答案:

答案 0 :(得分:2)

加入两次:

SELECT cars.id
  FROM cars
  JOIN car_properties AS cp1
    ON cp1.car_id = cars.id
   AND cp1.property_id = 1
  JOIN car_properties AS cp2
    ON cp2.car_id = cars.id
   AND cp2.property_id = 2
;