简体   繁体   English

将列从 integer[] 更新为 jsonb[]

[英]Update column from integer[] to jsonb[]

First off, for this I'm using Elixir (Ecto) but I think I'll be better off running a raw SQL statement on the migration.首先,为此我使用 Elixir (Ecto),但我认为我最好在迁移时运行原始 SQL 语句。

I have a column which is an array of integers;我有一列是整数数组; due to requirement changes I need to convert this array of integers to an array of objects, jsonb[] in this case.由于需求更改,我需要将此整数数组转换为对象数组,在本例中为jsonb[] This isn't looking quite right for me since converting from integer[] to jsonb[] is not possible (At least not automatically)这对我来说看起来不太合适,因为从integer[]转换为jsonb[]是不可能的(至少不是自动的)

I've been trying to cast both types but its just not resulting;我一直在尝试同时转换这两种类型,但它只是没有结果; I've even tried to convert to string then to jsonb but that doesn't seem to work.我什至尝试转换为字符串然后转换为 jsonb 但这似乎不起作用。

Now I'm looking for the best way to do this, not the simplest, just the best or correct way to do this.现在我正在寻找最好的方法来做到这一点,而不是最简单的,只是最好或正确的方法来做到这一点。 I was thinking about creating a temp column, copying the values from the old column there and renaming maybe?我正在考虑创建一个临时列,从那里的旧列中复制值并重命名? What would be the correct SQL statement for this?什么是正确的 SQL 声明?

By the way, I'm getting hit by this hint too hint: You might need to specify "USING table_name::jsonb[]" but using USING column_name::jsonb[] does not do the trick, neither CAST (column_name as jsonb) . USING column_name::jsonb[]说一句,我也被这个提示hint: You might need to specify "USING table_name::jsonb[]" CAST (column_name as jsonb) .

If it was as simple as I thought it would work with ALTER TABLE table_name ALTER COLUMN column_name TYPE jsonb[] USING column_name::jsonb[] .如果它像我认为的那样简单,它可以与ALTER TABLE table_name ALTER COLUMN column_name TYPE jsonb[] USING column_name::jsonb[] Let me know if I've not provided enough information, thanks.如果我没有提供足够的信息,请告诉我,谢谢。

One option is to use array_to_json() and then cast to jsonb or just to_jsonb() :一种选择是使用array_to_json()然后转换为 jsonb 或只是to_jsonb()

select x.*, array_to_json(ari)::jsonb,
       to_jsonb(ari)
from (select array[1, 2, 3] as ari) x;

If you want to change the type in place, use alter table :如果要更改类型,请使用alter table

alter table t alter column ari type jsonb using to_jsonb(ari);

Here is a db<>fiddle. 是一个 db<>fiddle。

The below construct will work to get you a JSONB[] from INT[].下面的构造将用于从 INT[] 获取 JSONB[]。 But technically what you get is not an array of JSON objects (which refers specifically to the hash-table like thingies), it just an array of JSON thingies which each contain a scalar with the JSON type of "number".但从技术上讲,你得到的不是 JSON对象的数组(专门指类似哈希表的东西),它只是一个 JSON 东西的数组,每个都包含一个“Z0ECD11C1D7A28742F8ZD14”类型的标量。 If that isn't what you want, you will have to describe what you want.如果那不是您想要的,您将不得不描述您想要的。

ALTER TABLE table_name ALTER COLUMN column_name TYPE jsonb[] USING column_name::text::jsonb[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM