初始化操作
创建表
CREATE TABLE orders ( "ID" int8 NOT NULL,
"info_j" json NOT NULL,
"info_t" text NOT NULL
);
初始化表
INSERT INTO orders("ID", "info_j","info_t") VALUES (1, '{"name":"张三","items":{"product":"啤酒","qty":6}}','{"name":"张三","items":{"product":"啤酒","qty":6}}');
INSERT INTO orders("ID", "info_j","info_t") VALUES (2, '{"name":"李四","items":{"product":"辣条","qty":8}}','{"name":"李四","items":{"product":"辣条","qty":8}}');
INSERT INTO orders("ID", "info_j","info_t") VALUES (3, '{"name":"王五","items":{"product":"苹果","qty":18}}','{"name":"王五","items":{"product":"苹果","qty":18}}');
INSERT INTO orders("ID", "info_j","info_t") VALUES (4, '{"name":"赵一","items":{"product":"香蕉","qty":20}}','{"name":"赵一","items":{"product":"香蕉","qty":20}}');
查询表
解析JSON字段
查询使用->操作符,查询json中所有顾客作为键
SELECT info_j -> 'name' AS customer FROM orders;
下面使用->>操作获取所有顾客姓名作为值
SELECT info_j ->> 'name' AS customer FROM orders;
根据json对象的key查询值
SELECT info_j -> 'items' ->> 'product' AS customer FROM orders;
解析TEXT中的JSON字段
其实和解析JSON字段一样我们只需要加上::json