首页 > 解决方案 > 仅返回与 IN 子句中指定的所有值匹配的行

问题描述

我在这里问了一个问题 -只选择那些与 IN 子句下指定的所有值匹配的行
但是,我错过了某些细节,因此再次询问正确的表信息。

我的桌子是这样的:

create table cars(
  model int,
  color varchar(10),
  fuel varchar(10),
  engine varchar(10),
  primary key (model, engine)
);

insert into cars values
(1081, 'blue', 'petrol', 'ec41'),
(1082, 'cyan', 'diesel', 'ec41'),
(1083, 'gray', 'diesel', 'ec41'),
(1084, 'gold', 'petrol', 'ec41'),

(1081, 'green', 'petrol', 'dc41'),
(1082, 'white', 'diesel', 'dc41');

将此集作为in子句的输入 - 模型(1081、1082、1083),我希望输出为:

(1081, 'blue', 'petrol', 'ec41')
(1082, 'cyan', 'diesel', 'ec41')
(1083, 'gray', 'diesel', 'ec41')

在这里,row(1084, 'gold', 'petrol', 'ec41')被忽略了。
此外,没有从引擎“dc41”中选择任何行,因为它没有所有提供的模型(缺少 1083)。

在帮助下,从我上一个问题的答案中,我想出了这种不恰当的查询:

select *
from car
where model in (1081,1082,1083)
and engine in (
       select engine
       from car where model in (1081,1082,1083)
       group by engine
       having count(distinct model) = 3
)

提供给 in 子句的值的数量是可变的。它可以是 3 或 4 或 5。
我必须放置一个外部选择,因为聚合函数不允许选择其他列。

我怎样才能正确地做到这一点?非常感谢。

标签: mysqlsql

解决方案


推荐阅读