【问题标题】:PostgreSQL - counting the elements in the JSONPostgreSQL - 计算 JSON 中的元素
【发布时间】:2016-06-30 12:01:32
【问题描述】:

我有一个名为“log_data”的 JSON 类型列,其中存储的数据格式为 [{"key":"test123123","identity":"user@test.it","identity_type":"email"}]

我想计算json中给定键的给定值的记录数:

不起作用

SELECT count (distinct esas_logs.log_id) AS "count" FROM "esas_logs" WHERE log_data->0->>'identity' = 'user@test.it'

[2016-06-30 13:59:18] [42883] ERROR: operator does not exist: json = unknown
  HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

【问题讨论】:

  • esas_logs.log_id 列的类型是什么?

标签: arrays json postgresql


【解决方案1】:

使用json_array_length()

test=# select  json_array_length('[{"key":"test123123","identity":"user@test.it","identity_type":"email"}]');
  json_array_length 
 -------------------
             1
 (1 row)

【讨论】:

  • 如果字段设置为jsonb,则改用jsonb_array_length()方法。
【解决方案2】:

根据doc,您应该使用? 运算符。

如果您的列类型是 JSON:

SELECT COUNT(esas_logs ? 'log_id') FROM esas_logs WHERE ...

如果您的列是 TEXT 或 VARCHAR:

SELECT COUNT(esas_logs::jsonb ? 'log_id') FROM esas_logs WHERE ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多