[英]convert jsonb column value to multiple columns in 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中進行選擇):
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"}]
希望大家能幫助我解決這個問題
在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.