繁体   English   中英

要在 Postgres 中使用的条件 IN 语句 function

[英]Conditional IN Statement to be used inside Postgres function

我正在研究 Postgres,我有两个表车辆和车辆标志。 两个表之间没有关系,因此我们不能连接两个表来获取所需的数据。 表结构如下(vehicle_flag 表可能不包含车辆表中存在的所有 id):

【表结构】 在此处输入图像描述

我正在编写一个接受多个输入参数的 function。 仅当标志值为 true 时,我才必须从 vehicle_flag 表中获取 select 车辆 ID:否则,我必须忽略 vehicel_flag 表。 我的目标是实现这样的目标,但结果证明 case 语句需要缩放器 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)

请提出任何解决方案来实现这一目标。

我怀疑你想要:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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