【问题标题】:Postgres query on json with empty value具有空值的 json 的 Postgres 查询
【发布时间】:2020-11-10 07:23:43
【问题描述】:

我在 JSON 中有一个查询,以根据 JSON 字段中存在的数据过滤掉数据。

表名:audit_rules 列名:rule_config (json)

rule_config 包含 JSON,其中包含 'applicable_category' 作为属性。

例子

{
   "applicable_category":[
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Meal",
         "acceptable_variation":0.18,
         "minimum_value":25.0
      },
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Car Rental",
         "acceptable_variation":0.0,
         "minimum_value":25.0
      },
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Airfare",
         "acceptable_variation":0.0,
         "minimum_value":75
      },
      {
         "status":"active",
         "supported":"yes",
         "expense_type":"Hotel",
         "acceptable_variation":0.0,
         "minimum_value":75
      }
   ],
   "minimum_required_keys":[
      "amount",
      "date",
      "merchant",
      "location"
   ],
   "value":[
      0,
      0.5
   ]
}

但有些行没有任何数据或其中没有 'applicable_category' 属性。

所以在运行以下查询时出现错误:

select s.*,j from 
  audit_rules  s 
   cross join lateral json_array_elements ( s.rule_config#>'{applicable_category}' ) as j
WHERE j->>'expense_type' in ('Direct Bill');

错误:SQL 错误 [22023]:错误:无法在标量上调用 json_array_elements

【问题讨论】:

  • 您用三个不同的、不受支持的 Postgres 版本(其中一个甚至不支持 JSON)标记了这个问题。您真正使用的是哪个 Postgres 版本?
  • PostgreSQL 9.6.18 on x86_64-pc-linux-gnu,由 gcc (GCC) 4.9.3 编译,64 位

标签: json postgresql postgresql-9.6


【解决方案1】:

您可以将结果限制为仅包含数组的行:

select j.*
from audit_rules  s 
   cross join lateral json_array_elements(s.rule_config#>'{applicable_category}') as j
WHERE json_typeof(s.rule_config -> 'applicable_category') = 'array'
  and j ->> 'expense_type' in ('Meal')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2015-11-28
    • 1970-01-01
    • 2022-07-02
    • 2023-03-09
    • 2015-05-19
    • 2013-02-26
    相关资源
    最近更新 更多