如何计算某些字段是否全部不为空?

How to calculate whether certain fields are all not null?

假设我有一个 table "articles",其中包含列 "author"、"title"(可为空)和 "body"(可为空)。当我查询这个 table 时,我想得到第四列:一个布尔值,表示 "title" 和 "body" 是否都已设置。我如何使用 Postgres 做到这一点?

我不想存储这第四列。我希望它是动态计算的,所以我希望我可以做类似的事情:

SELECT author, title, body, ALL(title, body) AS is_complete FROM articles;

我找不到任何方法来完成这个。有人有什么指点吗?

提前致谢。

只需检查 IS NULL

SELECT author, 
       title, 
       body, 
       title is not null and body is not null as is_complete 
FROM articles;

另一种方法是连接两列。如果其中一个是 null,则结果也将为 null(或者反过来:只有当两者都不为 null 时,串联的结果才会不为 null):

SELECT author, 
       title, 
       body, 
       title||body is not null is_complete 
FROM articles;

如果你想将空值 ('') 视为与 NULL 值相同,你需要使用类似的东西:

SELECT author, 
       title, 
       body, 
       coalesce(title,'') = '' and coalesce(body,'') = '' as is_complete 
FROM articles;

如果您经常需要这个,您可以基于这个查询创建一个视图。

您可以在行表达式上使用 IS NOT NULL,例如:

SELECT author, title, body, ROW(title, body) IS NOT NULL AS is_complete FROM articles;

spec,意思是:

If the expression is row-valued, then IS NULL is true when the row expression itself is null or when all the row's fields are null, while IS NOT NULL is true when the row expression itself is non-null and all the row's fields are non-null.

(...)

This definition conforms to the SQL standard, and is a change from the inconsistent behavior exhibited by PostgreSQL versions prior to 8.2.

您也可以使用 case when 语句

SELECT author, 
       title, 
       body, 
       case when title is not null and body is not null then 1 else 0 end as is_complete 
FROM articles;