将jsonb列值转换为PostgreSQL中的多个列

时间:2014-06-09 04:55:50

标签: php sql postgresql

假设我在PostgreSQL中有一个表,其中包含以下列:

CREATE TABLE sample
(
id int,
jsonb jsonb,
date date
)

我插入了这两行:

INSERT INTO sample
(id,jsonb,date)
VALUES
(1, '{"a":"a","b":"b"}', '2014/01/06'),
(2, '{"a":"a","b":"b"}', '2014/01/06')

我想将上述行转换为此内容(在PostgreSQL中执行select):

1,"a","b",'2014/01/06'
2,"a","b",'2014/01/06'

在php json_encode(rows from sample)

中调用

得到这样的东西:

[{"id":1,"a":"a","b":"b","date":"2014/01/06"},
{"id":2,"a":"a","b":"b","date":"2014/01/06"}]

但现在如果我在php json_encode(rows from sample)中调用,我会得到这个:

[{"id":1,"jsonb":"{"a":"a","b":"b"}","date":"2014/01/06"},
{"id":2,"jsonb":"{"a":"a","b":"b"}","date":"2014/01/06"}]

希望有人能帮助我解决这个问题,感谢所有人

1 个答案:

答案 0 :(得分:3)

在9.4中很简单(使用了LATERAL join和jsonb函数):

    postgres=# SELECT * 
                  FROM sample, jsonb_to_record(jsonb, true) AS x(a text, b text);
     id |            jsonb             |    date     |  a   |   b    
    ----+------------------------------+-------------+------+--------
      1 | {"a": "a", "b": "b"}         | 2014-01-06  | a    | b
      2 | {"a": "a", "b": "b"}         | 2014-01-06  | a    | b
      3 | {"a": "Ahoj", "b": "Nazdar"} | 2014-01-06  | Ahoj | Nazdar
    (3 rows)

确切的结果:

postgres=# SELECT id, a, b, date 
               FROM sample, jsonb_to_record(jsonb, true) AS x(a text, b text);
 id |  a   |   b    |    date    
----+------+--------+------------
  1 | a    | b      | 2014-01-06
  2 | a    | b      | 2014-01-06
  3 | Ahoj | Nazdar | 2014-01-06
(3 rows)