可以说我在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)
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 =#选择* FROM sample,jsonb_to_record(jsonb,true)AS x(a文本,b文本); id | jsonb | 日期| 一个| b ---- + ------------------------------ + ------------- + ------ + -------- 1 | {“ a”:“ a”,“ b”:“ b”} | 2014-01-06 | 一个| b 2 | {“ a”:“ a”,“ b”:“ b”} | 2014-01-06 | 一个| b 3 | {“ a”:“ Ahoj”,“ b”:“ Nazdar”} | 2014-01-06 | Ahoj | 纳兹达 (3列)
确切结果:
postgres =#SELECT ID,A,B,日期 FROM sample,jsonb_to_record(jsonb,true)AS x(a文本,b文本); id | 一个| b | 日期 ---- + ------ + -------- + ------------ 1 | 一个| b | 2014-01-06 2 | 一个| b | 2014-01-06 3 | Ahoj | 纳兹达尔| 2014-01-06 (3列)