【问题标题】:Query for records with excluded json value and where json key doesn't exist at the same time查询排除了json值且json键不存在的记录
【发布时间】: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', ... }

提前谢谢你。

【问题讨论】:

    标签: json ruby-on-rails postgresql ruby-on-rails-5 jsonb


    【解决方案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"
    

    【讨论】:

    • 它会选择那些没有关键评级的对象吗?
    猜你喜欢
    • 2021-09-16
    • 2016-11-10
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多