SQL 查询 json 列

SQL query with json column

我有一个 table 个人客户,其 employmentDetails 列作为 json 字段。 任务是获取位置字段为空的客户

[{
"employmentStatus": "E",
"communicationInfo": {
  "addresses": [
    {
      "id": "1",
      "houseName": "1",
      "locality": null
    }
  ]
}}]

我尝试了几种转换等变体但没有成功,请帮助我了解如何从 json 对象字段进行查询。我低于该值的尝试应该 return 一些值,但 return 什么也没有。

SELECT * FROM crm."IndividualCustomer" AS ic
WHERE (ic."employmentDetails" -> 'employmentStatus')::text = 'E';

SELECT * FROM crm."IndividualCustomer" AS ic
WHERE ic."employmentDetails" -> 'communicationInfo' -> 'adresses[0]' ->> 'locality' = null;

SELECT * FROM crm."IndividualCustomer" AS ic
WHERE ic."employmentDetails" -> 'communicationInfo' -> 'adresses' ->> 'locality' = null; 

The task is to get a customer that has empty locality field

您可以使用 JSON 路径表达式:

SELECT * 
FROM crm."IndividualCustomer" AS ic
WHERE ic."employmentDetails" @@ '$[*].communicationInfo.addresses[*].locality == null'

这需要 Postgres 12 或更高版本。如果您使用的是旧版本,则可以使用包含运算符 @>:

WHERE ic."employmentDetails" @> '[{"communicationInfo": {"addresses": [{"locality": null}]}}]'

这假设 "employmentDetails" 被定义为 jsonb(它应该是)。如果不是,则需要转换它:"employmentDetails"::jsonb.


条件:(ic."employmentDetails" -> 'employmentStatus')::text = 'E' 不成立,因为 -> return 是一个 jsonb(或 json)值转换为适当的 text 值(如果这样做,双引号将保留)。

您需要使用 ->> 运算符,它 return 直接是一个 text 值:(ic."employmentDetails" ->> 'employmentStatus') = 'E'

但是,顶级对象是一个数组,因此您需要选择例如第一个数组元素:

(ic."employmentDetails" -> 0 ->> 'employmentStatus') = 'E'

注意 -> 到 return 第一个数组元素作为正确的 jsonb 值,然后对该值使用 ->>

这也可以使用 JSON 路径表达式搜索所有数组元素来完成:

WHERE ic."employmentDetails" @@ '$[*].employmentStatus == "E"'`