微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在postgresql中对未知数量的布尔值执行AND?

我有一个带有外键和布尔值的表(以及一堆其他与此无关的列),如下所示:
CREATE TABLE myTable
(
  someKey integer,someBool boolean
);

insert into myTable values (1,'t'),(1,(2,'f'),'t');

每个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;

……给出了正确的结果:

select do_and(1) => t
select do_and(2) => f
select do_and(3) => null

我想知道是否有更好的方法来做到这一点.在这个简单的场景中看起来并不太糟糕,但是一旦你包含了所有支持代码,它就会比我想要的更长.我看一下将someBool列转换为数组并使用ALL构造,但是我无法使它工作……任何想法?

无需重新定义Postgresql已经提供的功能bool_and()将完成这项工作:
select bool_and(someBool)
  from myTable
  where someKey = $1
  group by someKey;

(抱歉,现在无法测试)

原文地址:https://www.jb51.cc/postgresql/191939.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐