【问题标题】:Create a table using data from another's table column that is in JSON form使用来自另一个表列的 JSON 格式的数据创建表
【发布时间】:2020-09-17 15:21:18
【问题描述】:

我正在使用 Postgres 服务器。这是我的桌子的样子

表示每部电影的流派栏目是:

[
    {'id': 18, 'name': 'Drama'},
    {'id': 36, 'name': 'History'},
    {'id': 10749, 'name': 'Romance'}
]

如您所见,每部电影的类型都在 VARCHAR 变量和 JSON 数组中。

我要做的是解压 JSON 的内容并创建一个名为 Genres 的新表,该表将为每个类型提供一次具有唯一 ID。

所以对于上面的示例,我希望我的新表如下所示:

id  | genre
18  | 'Drama'
36  | 'History'.

我该怎么做?

【问题讨论】:

  • 如果您使用 Postgres,为什么要标记 SQL Server?

标签: sql json postgresql postgresql-9.5


【解决方案1】:

您应该明确修复您的架构,并将您的 JSON 数据存储为 JSON[B] 数据类型而不是字符串。

也就是说,一种选择是强制转换为 json,这样我们就可以使用 Postsgres 强大的 json 函数来取消嵌套数组并访问内部对象。就您的数据显示而言,您只需将单引号转换为双引号即可使字符串有效 Postgres JSON,因此应该可以:

insert into genres(id, genre)
select distinct js ->> 'id', js ->> 'name'
from mytable t
cross join lateral jsonb_array_elements( (replace(genres, ''', '"'))::jsonb ) j(js)

【讨论】:

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