如何在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;

(抱歉,现在无法测试)

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...