返回JSONB作为Postgres中的行

发布于 2025-02-07 13:38:59 字数 1156 浏览 2 评论 0原文

我有一个JSON列,该列包含包含“名称”属性的对象数组。我正在尝试构建一个可以从所有行中提取所有对象的唯一名称的查询。

这是数据的样子:

[{
  "date": "2022-06-14T12:51:24.424Z",
  "name": "review_1"
}]

[{
  "date": "2022-06-14T12:50:56.454Z",
  "name": "review_3"
}, {
  "date": "2022-06-14T12:51:10.695Z",
  "name": "review_6"
}]

[{
  "date": "2022-06-14T12:51:57.997Z",
  "name": "review_3"
}]

[{
  "date": "2022-06-14T12:52:17.442Z",
  "name": "review_1"
}, {
  "date": "2022-06-14T12:54:35.239Z",
  "name": "review_9
}]

我的方法是将所有名称作为这样的单个行,以便我可以找到独特的。

name    ||  date
review_1    2022-06-14T12:51:24.424Z
review_3    2022-06-14T12:50:56.454Z
review_6    2022-06-14T12:51:10.695Z
review_3    2022-06-14T12:51:57.997Z
review_1    2022-06-14T12:52:17.442Z
review_9    2022-06-14T12:54:35.239Z

我已经尝试使用 JSONB_ARRAY_ELEMENTS 遵循此帖子 Postgres + JSONB +从多维数组中获取键的值,但看起来这是用于多维数组的,我无法使其工作。

I have a json column that holds an array of objects containing a 'name' attribute. I'm trying to build a query that can extract the unique names out of all the objects, across all rows.

Here is what the data looks like:

[{
  "date": "2022-06-14T12:51:24.424Z",
  "name": "review_1"
}]

[{
  "date": "2022-06-14T12:50:56.454Z",
  "name": "review_3"
}, {
  "date": "2022-06-14T12:51:10.695Z",
  "name": "review_6"
}]

[{
  "date": "2022-06-14T12:51:57.997Z",
  "name": "review_3"
}]

[{
  "date": "2022-06-14T12:52:17.442Z",
  "name": "review_1"
}, {
  "date": "2022-06-14T12:54:35.239Z",
  "name": "review_9
}]

My approach is to get all the names as individual rows like this so I can find the distincts.

name    ||  date
review_1    2022-06-14T12:51:24.424Z
review_3    2022-06-14T12:50:56.454Z
review_6    2022-06-14T12:51:10.695Z
review_3    2022-06-14T12:51:57.997Z
review_1    2022-06-14T12:52:17.442Z
review_9    2022-06-14T12:54:35.239Z

I've tried using jsonb_array_elements following this post postgres + jsonb + get values of key from multidimentional array but it looks like that is for multidimentional arrays and I cannot get it to work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝礼 2025-02-14 13:38:59

很难猜测您遇到的问题是什么样的问题,但是该功能的使用似乎很简单。

select elem->>'name' as "name", elem->>'date' as "date"
from my_table
cross join jsonb_array_elements(json_col) as arr(elem);

It is hard to guess what kind of problems you have encountered, but the use of the function seems quite simple.

select elem->>'name' as "name", elem->>'date' as "date"
from my_table
cross join jsonb_array_elements(json_col) as arr(elem);

Test it in Db<>fiddle.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文