One - One Code All

Blog Content

postgresql里json与jsonb中的-> 和 ->>区别

PostgreSQL   2020-04-12 09:31:35

 postgresql里json与jsonb中的-> 和 ->>区别


示例:


mytest=# SELECT '[{"a":1},{"b":2},{"c":3}]'::JSON -> 1 -> 'b';

 ?column?

----------

 2

(1 行记录)



mytest=# SELECT '[{"a":1},{"b":2},{"c":3}]'::JSON ->> 1 -> 'b';

错误:  操作符不存在: text -> unknown 第1行

-- 操作符不存在,因为第一步查询出来的是一个字符串,不是JSON对象。


SELECT '[{"a":1},{"b":2},{"c":3}]'::JSON ->> 1 -> 'b';

                                                    ^

提示:  No operator matches the given name and argument types. You might need to add explicit type casts.


-- 我们将第一步查询出来的字符串转成JSON对象,然后通过 Key 的方式来获取 Value。

mytest=# SELECT ('[{"a":1},{"b":2},{"c":3}]'::JSON ->> 1)::JSON -> 'b';

 ?column?

----------

 2


 结论:


 1. -> 表示获取一个JSON数组元素,支持下标值(下标从0开始)、Key获取。->> 表示获取一个JSON对象字符串。

 2. #> 表示获取指定路径的一个JSON对象,#>>表示获取指定路径的一个JSON对象的字符串。

 3. ::JSON 表示声明前面的字符串为一个JSON字符串对象,而且PostgreSQL中的JSON、JSONB对象 Key的声明必须是字符串 。



上一篇:同一个sql语句中返回多个count,count(1),count(null)
下一篇:数据迁移从ES到postgresql,logstash的logstash-input-jdbc插件安装

The minute you think of giving up, think of the reason why you held on so long.