如何根据不同行的左外连接关系的属性生成函数值

问题描述 投票:1回答:1

我有一张名为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。真正的表有数百万行,所以它需要相对较好的性能

sql postgresql aggregate-functions
1个回答
2
投票

你可以使用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;

DBFiddle Demo


没有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;

DBFiddle Demo2

编辑:

建议使用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;

DBFiddle Demo3

© www.soinside.com 2019 - 2024. All rights reserved.