--string_agg 相当于php里的implode
--array_to_string 把数组字段转成字符串
select string_agg(DISTINCT(array_to_string(app_ids, ',') ),',') as item FROM app_group;
数据类型:
smallint(3w、别名:int2)、integer(20亿,别名 int4)、bigint都是整数类型(20亿,别名 int8)
smallint = int2
integer = int =int4
bigint = int8
特色数据类型:array、inet、json、xml、serial、布尔、UUID 类型、几何类型
查看存储过程详情
SELECT prosrc FROM pg_proc WHERE proname = 'xxxxx';
关于自增
貌似要自己建序列,"id" int4 NOT NULL DEFAULT nextval('iot_client_id_seq'::regclass), --自增,其实就是 id serial NOT NULL
关于ip
"ip" inet, -- 用这些数据类型存储网络地址比用纯文本类型好, 因为这些类型提供输入错误检查和特殊的操作和功能
新增数组类型的:
INSERT INTO "Students" VALUES ('colin', '{"音乐", "电影", "读书"}') -- 原生
INSERT INTO "Students" VALUES ('colin', ARRAY['音乐', '电影', '读书'] ) -- 构造函数,只能单引号
数组其他操作
访问:select interest[1] from "Students" where id = 1 -- 不能加引号
取多个:select interest[1:2] from "Students" where id = 1
搜索:select "interest" from "Students" where '睡觉' = ANY("interest");
展开数组:select unnest("interest") from "Students" where '睡觉' = ANY("interest");
@> ==== contains
&& ==== 取交集
|| ==== 取并集 但要注意 数组与数组,元素与数组、数组与元素的情况
特点:1、可以直接访问元素;2、
坑:
注意1:双引号单引号这里不能混用:'{"音乐", "电影", "读书"}'
注意2:插入后在数据库查看是{音乐,电影,读书} ,而不是{'音乐','电影','读书'}
1、数组的形式不是 [] 包裹而是 {}
2、数组的索引不是从 0 开始而是从 1 开始
坑:
1、表名、字段名、别名等大小敏感,默认都会转化成小写形式
2、如果需要将已经创建的表字段,改为自增长,不能使用serial类型(有些客户端软件有bug,会提供这个类型,但是更改会报错)
3、postgresql中函数与存储过程是一个东西
4、postgresql中除了列名、表名等用来标识对象名称外尽量不要使用双引号,会被解释成列名的。字段如果是关键字,要加双引号
5、不可使用oracle中常用的查询更新语句,如果update tt set (c1,c2) = (select c1,c2 from ..),而必须使用update from 新语句,update tt set c1 = t2.c1 ,c2 = t1.c2 from t1(或者子查询)
6、在查询数据时,NULL 值可能会导致一些问题,因为一个未知的值去与其他任何值比较,结果永远是未知的
json类型
特点:1、select和where中可以指定元素
场景:
性能:
坑:
比text好处:1、保证是可用的json;2、可用相关json函数
特殊写法:
select NULLIF(ip_addr->0->>'address', '')::inet as ip from -- 类型转换??
gid = ANY(
select array_to_json(array_agg(row_to_json(t)))
例子:select array_to_json(array_agg(row_to_json(t))) from (select id, name from iot_serv_group) t;
结果:[{"id":6,"name":"1111555511"},{"id":7,"name":"aa"}]
函数
将结果集封装成JSON
row_to_json:每一行都是json
{"id":6,"name":"1111555511"}
{"id":7,"name":"aa"}
array_agg:变成一个数组
{"{\"id\":6,\"name\":\"1111555511\"}","{\"id\":7,\"name\":\"aa\"}"}
array_to_json:数组转json
[{"id":6,"name":"1111555511"},{"id":7,"name":"aa"}]
json_extract_path_text -- 忽略json错误
select array_to_json(array_agg(row_to_json(t)))
类型转换:as integer
coalesce:处理空值,从左到右有一个不为空就返回
ifnull:判断是否为null
CAST:类型转换
CAST(coalesce(iar.count_gid,0) as integer):转成int,给默认值0
解析json
运算符->按键返回JSON对象字段
运算符->>按文本返回JSON对象字段
例子:select unnest(visit_group_ids) from iot_node where mid=1111111;
结果:
11111111
22222222
json与数组区别及场景?
oid是什么?是否有oid是什么?
规律总结:
不用引号:内置函数、当键名是数组而取索引值时
单引号:值、当键名是数组而取索引值时、json字段取value值("edu_experience"->'name')
双引号:表名、键名、值里面嵌套的值
插入冲突时:
PostgreSQL 9.5以前的版本,可以通过函数或者with语法来实现与UPSERT类似的功能。
insert into ke_topic_rank values ('test1','test2','test3', 7) on conflict (cluster,topic,tkey) do update set tvalue=excluded.tvalue;
INSERT INTO test.upsert_test(id, "name")
VALUES(1, 'm'),(2, 'n'),(4, 'c')
ON conflict(id) DO NOTHING;