简体   繁体   中英

Conditional IN Statement to be used inside Postgres function

I am working on Postgres and I have two tables vehicles and vehicles_flag. There are no relations between the two tables and hence we can not join two tables to fetch the required data. The table structure is below (vehicle_flag table may not contain all the id present in the vehicle table):

[Table structure] 在此处输入图像描述

I am writing a function that will accept multiple input parameters. I have to select vehicle id from the vehicle_flag table only if the flag value is true: otherwise, I have to ignore the vehicel_flag table. My aim is to achieve something like this, but turns out the case statement expects scaler output:

select count(id) from vehicles
where 
vehicles.id in (case
when @hasbluetooth =1 then (select distinct id from vehicle_flags where flag='bluetooth' and       value = '1')
else
(select distinct id from vehicles)
end)

and

vehicles.id in (case
when @hasac =1 then (select distinct id from vehicle_flags where flag='ac' and value = '1')
else
(select distinct id from vehicles)
end)

Kindly suggest any solution to achieve this.

I suspect you want:

select v.*
from vehicle v
left join vehicle_flags vf on vf.id = v.id
group by v.id
having
    (@hasbluetooth = 0 or bool_or(vf.flag = 'bluetooth' and vf.value = 1)
    and (@hasac = 0 or bool_or(vf.flag = 'ac' and vf.value = 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM