【问题标题】:postgresql query json sub elements in where clause or alternative for json_exists() oracle funtion in postgresqlpostgresql查询where子句中的json子元素或postgresql中json_exists()oracle函数的替代方法
【发布时间】:2019-12-30 06:59:26
【问题描述】:

我有一些类似于下面的 json 的 json 存储在 postgres json 列中。我必须准备 json 的 where 条件,例如 mobile 类型的 entrySource 是否等于 true 以及 timeSheetEntry 对象是否存在。

Json 样本:

[
  {
    "calculationMethodID": "TimeEntryCommon",
    "inputs": {
      "defaultStartTime": "08:00",
      "supportedEntryTypes": {
        "timeSheetEntry": {
          "type": "TotalHours"
        }
      },
      "maxShift": {
        "breakDuration": "PT2H",
        "length": "PT14H"
      }
    }
  }
]

[
  {
    "calculationMethodID": "TimeEntryCommon",
    "inputs": {
      "defaultStartTime": "08:00",
      "supportedEntryTypes": {
        "punchEntry": {
          "entryCodes": [
            "In",
            "TakeMeal",
            "Out"
          ],
          "entrySource": {
            "mobile": true,
            "clock": true,
            "ivr": false,
            "web": true
          }
        }
      },
      "maxShift": {
        "breakDuration": "PT2H",
        "length": "PT14H"
      }
    }
  }
]

我写了这个sql条件来检查json数据是否包含特定的对象/值,这里'client_policy_js'是json类型的列名:

查询

SELECT p.pol_name,p.pol_oid FROM PYR_CLIENT_POLICY_OPTION p
WHERE p.status    =1
AND (json_exists(client_policy_js, '$?        
(@.inputs.supportedEntryTypes.punchEntry.entrySource.clock == true)')
OR json_exists(client_policy_js, 
'$.inputs.supportedEntryTypes.timeSheetEntry'))
AND ((p.eff_date BETWEEN TRUNC(sysdate) AND TRUNC(sysdate))
OR (p.eff_date_end BETWEEN TRUNC(sysdate) AND TRUNC(sysdate))
OR (p.eff_date     < TRUNC(sysdate)
AND p.eff_date_end > TRUNC(sysdate)))

请帮助我在 PostgreSQL 中使用以下 oracle 查询的替代方法:

WHERE (json_exists(client_policy_js, '$?(@.inputs.supportedEntryTypes.punchEntry.entrySource.clock == true)') 
   OR json_exists(client_policy_js, '$.inputs.supportedEntryTypes.timeSheetEntry'))

【问题讨论】:

  • 请写出更好的问题

标签: java json oracle postgresql


【解决方案1】:

如果您使用的是 Postgres 12,您可以简单地将 json_exists() 替换为 jsonb_path_exists()

WHERE (jsonb_path_exists(client_policy_js, '$?(@.inputs.supportedEntryTypes.punchEntry.entrySource.clock == true)') 
       OR jsonb_path_exists(client_policy_js, '$.inputs.supportedEntryTypes.timeSheetEntry'))

如果您使用的是旧版本,则需要使用#&gt;&gt; 运算符提取指定路径处的值。使用-&gt; 运算符获取第一个数组元素:

WEHERE (client_policy_js -> 0 #>> '{inputs,supportedEntryTypes,punchEntry,entrySource,clock}'::text[] = 'true'
        OR client_policy_js -> 0 #>> '{inputs,supportedEntryTypes,timeSheetEntry}'::text[] is not null)

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多