将Postgres列迁移到JSON列

时间:2015-08-17 11:04:23

标签: json postgresql sql-update

如何将整数列foo迁移到json数组列bar

这不起作用,因为m2不是有效的json表达式...

UPDATE mytable SET bar='[m2.foo]' 
FROM (
  SELECT m.foo FROM mytable WHERE bar IS NULL
) AS m2 
WHERE bar IS NULL

在更新查询之前:

+----+-----+
|bar | foo |
+====+=====+
 null   1
 null   2
 null   3
 null   4

查询后(预期结果):

+----+-----+
|bar | foo |
+====+=====+
 [1]   1
 [2]   2
 [3]   3
 [4]   4

1 个答案:

答案 0 :(得分:0)

以下是使用当前版本的方法:

create table test(bar json, foo int) ;

insert into test(bar , foo )
select array_to_json(array[bar]), foo 
from (
select i as bar, i as foo from generate_series(1,10) i
) m2 ;

select * from test ;

结果:

        [1] ; 1
[2] ;2
[3] ;3
[4] ;4
[5] ;5
[6] ;6
[7] ;7
[8] ;8
[9] ;9
[10] ;10


update test set bar= null

现在您的更新语句应如下所示:

update test set bar = array_to_json(array[m2.foo])
from (
select foo from test
) m2
where bar is null and m2.foo = test.foo;

select * from test ;

给出您在问题中指定的结果。