查询排除了json值且json键不存在的记录

Posted

技术标签:

【中文标题】查询排除了json值且json键不存在的记录【英文标题】:Query for records with excluded json value and where json key doesn't exist at the same time 【发布时间】:2022-01-11 23:56:10 【问题描述】:

我有一个students 表,其中有一个名为json 的json 列。它有不同的键。我想召唤没有rating 键的特定Fail 值的记录,同时记录不存在json 键rating 的记录。如何实现?

# Objects

json:  rating: 'Pass', ... 
json:  grade: 'A', ...
json:  rating: 'Fail', ... 

我基本上需要排除带有rating: 'Fail'的记录并返回所有其他对象,包括那些json键rating不存在的对象。

查询的结果应该如下:

json:  rating: 'Pass', ... 
json:  grade: 'A', ... 

提前谢谢你。

【问题讨论】:

【参考方案1】:

在 SQL 中你可以这样做:

select *
from students
where "json" ? 'rating'  -- only include those that have the key rating
  and not "json" @> '"rating": "fail"' -- don't include those with "fail"

【讨论】:

它会选择那些没有关键评级的对象吗?

以上是关于查询排除了json值且json键不存在的记录的主要内容,如果未能解决你的问题,请参考以下文章