PostgreSQL支持JSON和JSONB
这两种类型在使用上几乎完全一致,主要区别是:
- (1)JSON类型把输入的数据原封不动的存放到数据库中。JSONB类型在存放时把JSON解析成二进制格式。
- (2)JSONB支持在其上建索引,而JSON不能,这是JSONB的一个很大的优点。
- (3)JSON中会保留多余的空格,保留重复的Key,保留Key的顺序。JSONB则完全相反,不保留多余的空格,不保留重复的Key,不保留Key的顺序。
JSON测试SQL操作
-- 创建表
drop table if exists xh_yw.test_json;
create table xh_yw.test_json (
pk_uid int8 not null,
info json not null,
CONSTRAINT test_json_id_pkey PRIMARY KEY (pk_uid)
);
-- 插入数据
INSERT INTO xh_yw.test_json (pk_uid,info) VALUES
(1,'{ "customer": "Lily Bush", "items": {"product": "Diaper","qty": 24},"telephone":"13793002505"}'),
(2,'{ "customer": "Josh William", "items": {"product": "Toy Car","qty": 1}}'),
(3,'{ "customer": "Mary Clark", "items": {"product": "Toy Train","qty": 2}}');
-- 一般查询
select pk_uid,info from xh_yw.test_json;
-- JSON查询
select
pk_uid,
info -> 'telephone' AS telephone
from xh_yw.test_json;
-- JSON查询
select
pk_uid,
info -> 'telephone' AS telephone,
info -> 'items' AS items
from xh_yw.test_json where info -> 'telephone' is not null;
-- json子查询
select
pk_uid,
info -> 'telephone' AS telephone,
info -> 'items' ->> 'product' AS product
from xh_yw.test_json where info -> 'items' ->> 'product' = 'Diaper';
-- 表记录全部JSON返回
select row_to_json(test_json) as json from xh_yw.test_json;