【问题标题】:Boolean type in Postgres does not work as expectedPostgres 中的布尔类型无法按预期工作
【发布时间】:2018-03-28 08:03:29
【问题描述】:

我使用的是 Ubuntu 16.04 和 psql (PostgreSQL) 9.4.14。

我刚刚遇到了一个非常奇怪的案例。 boolean 的三个状态之和不等于整数。

这是deleted 字段属性默认为false。

我试过了:

全部计数:

SELECT count(*) from table; the count -> 9000

未删除的计数:

SELECT count(*) from table where deleted; the count -> 400;

同:

SELECT count(*) from table where deleted = true; the count -> 400;

删除次数:

SELECT count(*) from table where not deleted; the count -> 0; 

同:

SELECT count(*) from table where deleted <> true; the count -> 0;

null 的情况是:

SELECT count(*) from table where deleted = null; the count -> 0;

我检查了official doc

PostgreSQL 提供标准的 SQL 类型 boolean。 boolean 类型可以有几种状态:“true”、“false”,以及第三种状态“unknown”,由 SQL 空值表示。

但如您所见,三个州的最终总和不能是9000

出乎意料的恼火。

请为此提供一些建议,谢谢!

【问题讨论】:

  • SELECT count(*) from info_security_group where deleted IS null;,不等于
  • 这就是我总是将boolean 列定义为NOT NULL 并以false 作为默认值的原因之一

标签: postgresql boolean


【解决方案1】:

您需要使用IS NULL 将列与NULL 进行比较:

select count(*) from info_security_group where deleted is null;

我的猜测是这将返回 8600 的计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多