【问题标题】:Postgresql JSON column check value exists in array of jsonPostgresql JSON 列检查值存在于 json 数组中
【发布时间】:2021-07-14 16:50:22
【问题描述】:

我有一个类似于以下的数据库架构,其中有一个 Children 记录表

CREATE TABLE Children (
  name varchar(100),
  friends JSON NOT NULL,
);

INSERT INTO Children (name,friends)
VALUES('Sam',
        array['{"name":"Rakesh","country":"Africa"}', 
         '{"name":"Ramesh","country":"India"}']::json[]);


现在我需要查询数据并仅在朋友的名字像'%Ra'时显示它。 JSON数据的结构是一致的。

【问题讨论】:

  • 强制转换为json[] 对我来说毫无意义 - 它会导致错误“列“朋友”是 json 类型,但表达式是 json[] 类型"

标签: sql json postgresql


【解决方案1】:

如果您有json[] 作为数据类型,那么您可以使用unnest,然后编写您的查询,或者如果它是json,那么您可以使用json_array_elements

下面的代码考虑json[]数据类型-

select * from Children
where name in (
select name from (
select name, unnest(friends) as friend from Children
  ) i
where i.friend->>'name' like '%Ra');

DBFiddle

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-01-28
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2018-12-12
  • 2015-10-09
相关资源
最近更新 更多