我有一张名为cars
的表格。汽车与tires
表有一对多的关系。轮胎有一个名为condition
的栏,可以是“平”或“抽”。
我想查询一下,我可以计算出没有泵送轮胎的车数。这意味着所有轮胎必须是平的。为了让汽车被计算在内。我该怎么做
我正在尝试类似的事情:
SELECT COUNT(*)
FROM "cars"
left join tires on cars.id = tires.car_id
WHERE "tires"."condition" = 'flat'
AND "tires"."id" IS NULL
但这似乎并不完全正确......
这是一个数据样本。结果应该是1
的计数。只有身份3的汽车没有抽水轮胎
# Cars
id brand model
1 Audi A4
2 BMW X5
3 Ford Mondeo
# Tires
id car_id condition
1 1 flat
2 1 pumped
3 1 pumped
4 1 flat
5 2 pumped
6 2 pumped
7 2 pumped
8 2 pumped
9 3 flat
10 3 flat
11 3 flat
12 3 flat
修改
condition
和car_id
被编入索引并且有数百万行 - 所以它需要具有高性能
答案 0 :(得分:1)
计算所有没有任何抽水轮胎的汽车:
select count(*)
from cars c
where not exists (select 1 from tires t
where c.id = t.car_id
and t.condition = 'pumped')
答案 1 :(得分:0)
通常我会:
SELECT COUNT(*)
FROM cars
where not exists (select null
from tires
where tires.car_id = cars.id and
tires.condition = 'pumped')
但是,如果您的汽车比例非常小,而且任何轮胎都是“平坦的”,那么我会考虑首先将汽车过滤到候选清单,以便检查没有抽水轮胎。
SELECT COUNT(*)
FROM cars
where id in (select distinct id
from tires
where tires.condition = 'flat') and
not exists (select null
from tires
where tires.car_id = cars.id and
tires.condition = 'pumped')
你需要为后者设置索引(条件,car_id)和(car_id,condition)。
另一种可能感兴趣的方法是:
select count(*)
from (
select 0
from tires
group by car_id
having max(condition) = 'flat')