我有一张名为cars
的桌子,里面有许多images
。
我想为cars.id, cars.brand, (???some_query???) AS any_value_of_x_true
返回所有不同的行,其中any_value_of_x_true
是一个虚拟列,通过检查images
表中的任何相关行是否具有url = 'www.example.com'
和(images.data->'d'->>'x')::boolean IS TRUE
而生成
这是小提琴:http://sqlfiddle.com/#!15/d50d84/3
这是我正在寻找的结果:
id brand any_value_of_x_true
1 Bmw true
2 Audi false
3 VW false
PS。真正的表有数百万行,所以它需要相对较好的性能
你可以使用bool_or
:
bool_or(表达式)
如果至少有一个输入值为true,则为true,否则为false
SELECT cars.id, brand,
bool_or(CASE WHEN url = 'www.example.com'
and (images.data->'d'->>'x') = 'true' THEN true else false end)
AS any_value_of_x_true
FROM cars
LEFT JOIN images on cars.id = images.car_id
GROUP BY cars.id, brand
ORDER BY id;
没有CASE
作为@Hans Z建议:
SELECT cars.id, brand, COALESCE(bool_or(url = 'www.example.com'
and (images.data->'d'->>'x')::boolean), false)
FROM cars
LEFT JOIN images on cars.id = images.car_id
GROUP BY cars.id, brand
ORDER BY id;
编辑:
建议使用MAX
作为@ shawnt00:
SELECT cars.id, brand,
max(case when url = 'www.example.com' and (images.data->'d'->>'x')::boolean
then 1 else 0 end
)::boolean AS any_value_of_x_true
FROM cars
LEFT JOIN images on cars.id = images.car_id
GROUP BY cars.id, brand
ORDER BY id;