mysql 如何将多个相关的exist查询组合到一个查询中?

a5g8bdjr  于 2023-04-19  发布在  Mysql
关注(0)|答案(2)|浏览(136)

我有两个查询,我想对某种类型的产品运行,以检查是否存在具有某些规格的产品。
因此,我首先要检查一个产品是否包含type=A,如果是,再次检查它是否包含type=B or C。我如何将这两者组合到一个查询中?
桌汽车:

id;product;type
0;car;A
1;car;B
2;car;C

当前的两步SQL:

SELECT 1 FROM cars where product = 'car' and type = 'A';

如果是:

SELECT 1 FROM cars where product = 'car' AND (type = 'B' OR type = 'C');
7lrncoxx

7lrncoxx1#

听起来你需要将它们与 exists 组合在一起,比如

select *
from t
where product = 'car' and type = 'A'
and exists (
  select * from t t2
  where t2.product = t.product and t2.type in ('B', 'C')
);
mwkjh3gx

mwkjh3gx2#

假设product是表中的“分组”字段,您可能需要类似这样的东西。

SELCET * FROM cars c
WHERE EXISTS(SELECT 1 FROM cars where product = c.product and type = 'A')
AND EXISTS(SELECT 1 FROM cars where product = c.product AND type IN ('B', 'C'))
AND c.product = 'car'

相关问题