rjo*_*ton 7 sql postgresql plpgsql
我有一个带有外键和一个布尔值的表(以及一些其他与此无关的列),如下所示:
CREATE TABLE myTable
(
someKey integer,
someBool boolean
);
insert into myTable values (1, 't'),(1, 't'),(2, 'f'),(2, 't');
Run Code Online (Sandbox Code Playgroud)
每个someKey可以有0个或更多条目.对于任何给定的someKey,我需要知道a)所有条目是否为真,或b)任何条目都是假的(基本上是AND).
我想出了以下功能:
CREATE FUNCTION do_and(int4) RETURNS boolean AS
$func$
declare
rec record;
retVal boolean = 't'; -- necessary, or true is returned as null (it's weird)
begin
if not exists (select someKey from myTable where someKey = $1) then
return null; -- and because we had to initialise retVal, if no rows are found true would be returned
end if;
for rec in select someBool from myTable where someKey = $1 loop
retVal := rec.someBool AND retVal;
end loop;
return retVal;
end;
$func$ LANGUAGE 'plpgsql' VOLATILE;
Run Code Online (Sandbox Code Playgroud)
......给出了正确的结果:
select do_and(1) => t
select do_and(2) => f
select do_and(3) => null
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更好的方法来做到这一点.在这个简单的场景中看起来并不太糟糕,但是一旦你包含了所有支持代码,它就会比我想要的更长.我看一下将someBool列转换为数组并使用ALL构造,但我无法使它工作......任何想法?
小智 7
无需重新定义PostgreSQL已经提供的函数:bool_and()将完成这项工作:
select bool_and(someBool)
from myTable
where someKey = $1
group by someKey;
Run Code Online (Sandbox Code Playgroud)
(抱歉,现在无法测试)
| 归档时间: |
|
| 查看次数: |
1413 次 |
| 最近记录: |