给出表格:
parts (part_id, part_desc, type_id, car_id)
types (type_id, type_name)
cars (car_id, car_model, car_make)
我想找到汽车的id,型号和品牌,这些汽车的零件属于制造'本田'和模型'思域'的所有类型的零件。也就是说,如果Honda Civic的类型为A,B,C
,那么它会找到所有属于A
和B
以及C
的汽车。
我不确定如何执行此操作,但我设法为A
或B
或C
SELECT DISTINCT c.car_id, c.car_model, c.car_make
FROM cars c, parts p
WHERE c.car_id= p.car_id AND p.type_id IN (
SELECT p.type_id FROM cars c, parts p
WHERE a.car_id = p.car_id
AND a.car_model = 'Civic'
AND a.car_make = 'Honda'
)
如果内部查询获得本田思域的所有类型的部件,但如果它们只有A,B,C
中的一个而不是全部,那么IN()子句将匹配汽车。
我希望避免使用ALL
和ANY
集合运算符。另外A,B,C
就是一个例子,不应该在字面上用它在答案中硬编码。子查询的结果将是未知的。
答案 0 :(得分:0)
with t as ( -- first find out all the type_id belonging to Honda civic
select distinct p.type_id
from cars c
,parts p
where c.car_model = 'Civic'
and c.car_make = 'Honda'
and c.car_id = p.car_id
)
,c as ( -- find which car has which part types
select distinct
c.car_id
,c.car_make
,c.car_model
,t.type_id
from t
,parts p
,cars c
where t.type_id = p.type_id
and p.car_id = c.car_id
)
-- the number of the records in c for each car meeting conditions must be equal to
-- the number of part types
select c.car_id
,c.car_make
,c.car_model
from c
group
by c.car_id
,c.car_make
,c.car_model
having count(0) = (select count(0) from t)
答案 1 :(得分:0)
为避免像“所有”这样的词语,请使用两个否定来重新表达问题:
你想要的是本田思域没有类型的汽车,但这辆车没有。
SELECT *
FROM cars
WHERE NOT EXISTS (SELECT 1
FROM types CivicTypes
JOIN parts CivicParts USING (type_id)
WHERE car_id = (SELECT car_id
FROM cars
WHERE car_make = 'Honda'
AND car_model = 'Civic')
AND NOT EXISTS (SELECT 1
FROM types JOIN parts USING (type_id)
WHERE type_id = CivicTypes.type_id
AND car_id = cars.car_id)
)