【问题标题】:How to query array in Postgres json column?如何在 Postgres json 列中查询数组?
【发布时间】:2022-01-07 21:53:24
【问题描述】:

提前致谢。假设,我有一个表,其中包含类似这样的数组中的值。

CREATE TABLE example (
    id serial4 NOT NULL,
    name varchar(100) NOT NULL,
    content_type json NULL
    CONSTRAINT example_pkey PRIMARY KEY (id)
);
id |name |content_type
-----------------------
 1 | P   | ['a','b','c']
 2 | Q   | ['a',]
 3 | R   | ['b','c']
 4 | S   | ['a','c']

我想查找 content_type 中哪一行包含'c'

我试过了,但没有得到,

select * from table where ARRAY['c'] && content_type;

有人帮我构建查询吗?

【问题讨论】:

  • 你可以找到数组中所有值都等于 c 的行:SELECT * FROM table WHERE value = ALL (column);
  • 不清楚。 content_type 是 char 数组还是 JSON? Edit 问题并添加表的CREATE 声明以澄清。还有为什么这不是以关系方式建模的?这可以通过链接内容类型的另一个表轻松完成。那么这将是一个简单的连接查询......
  • @stickybit,谢谢你的建议。我本可以对关系方式进行建模,但由于某些原因,我必须遵循这一点。 content_type 是一个 JSON 列。
  • @RakibulIslam 你真的需要 JSON 列吗?它还可以保存对象或原始值而不是数组吗?数组可以包含字符以外的任何内容吗?如果没有,您应该将列类型更改为char[]text[],使其成为实际的数组列(并让Pooya 的答案起作用)
  • 再次感谢您。我会尝试在这里提供反馈。

标签: json postgresql postgresql-json


【解决方案1】:

更新了将列类型从 text[] 更改为 json

如果您的列类型是 JSON,您可以使用两种方案:

Demo

  1. 转换成jsonb并使用?操作符(Postgres document
select * from test where content_type::jsonb ? 'c';
  1. 使用json_array_elements_text
select distinct on(t.id) t.*
from 
  test t
  cross join json_array_elements_text(content_type) je
where
  je.value = 'c';

旧场景

您可以使用any函数检查数组中是否存在值或根据Postgres document使用数组运算符@>

Demo

  1. any
select * from test where 'c' = any(content_type);
  1. @>
select * from test where content_type @> array['c'];

【讨论】:

  • content_type的数据类型为JSON,显示“ERROR: op ANY/ALL (array) requires array on right side”
  • 我更新了 JSON 场景的帖子
猜你喜欢
  • 2017-10-19
  • 2013-09-20
  • 1970-01-01
  • 2017-04-03
  • 2016-06-05
  • 1970-01-01
  • 2015-11-28
  • 2018-05-20
相关资源
最近更新 更多