我有 2 张 table
cars
|id|name|car_type_id|
car_types
|id|name|
对于汽车来说,car_type_id
可以为 null。
我想查询我的数据库,以便获得汽车类型列表,以及每种car_type
的汽车数量。车型为null的车型可以为null。
我希望这是清楚的。但欢迎任何建议。
所以我希望找回类似的东西
car_type | count
car type 1 | 3
car type 2 | 4
uncategorized | 12
编辑: 所以我可以使用获取类型及其总数
select
car_type.id,
car_type.name,
(SELECT COUNT(*) FROM cars
WHERE cars.car_type_id = car_type.id) as tot
from car_type
但这并没有给我所有 car_type_id 为 null 的汽车
最佳答案
使用从 cars
到 car_types
的外部(即 left
)连接,但将 'uncategorized'
指定为没有连接的 car_type 名称。将其与反向联接结合起来,过滤出匹配的行。
select
coalesce(car_types.name, 'uncategorized') as car_type,
count(*) as tot
from cars
left join car_types on cars.car_type_id = car_types.id
group by 1
union
select car_types.name, 0
from car_types
left join cars on cars.car_type_id = car_types.id
where cars.car_type_id is null
union
select * from (select 'uncategorized', 0)
where exists (select * from cars where car_type_id is null)
仅供引用,coalesce()
从提供给它的值列表中返回第一个非空值,并且当以下情况时,左连接表中的所有列均为 null
没有匹配的行。
关于Postgresql - 获取计数和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44273071/