在 sql 中处理多对多关系

Handling a many to many relationship in sql

我有两个主要的 table。汽车和功能。一辆车有很多特征,一个特征可以有很多车。因此,一座桥梁 table 位于它们之间,称为 CARFEATURE。它具有 PKFKCarID 和 PKFKFeature ID。我想查询仅具有我指定的特定功能的汽车。我将如何使用 SQL 执行此操作。

我试过了,SELECT * FROM CARFEATURE WHERE FEADTUREID = 'GPS' AND FEATUREID = 'RADIO'。但是我最终得到了空结果。

多种选择。我猜你想要

select carID
  from carFeature
 where featureID in ('GPS', 'Radio')
 group by carID
having count(distinct featureID) = 2

你也可以

select carID
  from carFeature
 where featureID = 'GPS'
intersect
select carID
  from carFeature
 where featureID = 'Radio'

我认为后一个查询更清晰一些,但可能不如第一个查询有效。