postgresql 查询集合结果用逗号分隔返回字符串处理的操作

时间:2021-11-29 22:24:17

关键字:

?
1
string_agg('' , '')

例如:

?
1
select string_agg(name||'' , ',') from sys_user

postgresql 查询集合结果用逗号分隔返回字符串处理的操作

补充:PostgreSQL 字段用逗号 “,”隔开 判断是否含有某个值

Array Functions and Operators

https://www.postgresql.org/docs/9.2/functions-array.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
-- ----------------------------
-- Table structure for T_STUDENT
-- ----------------------------
DROP TABLE IF EXISTS "public"."T_STUDENT";
CREATE TABLE "public"."T_STUDENT" (
"id" int4,
"name" varchar(255) COLLATE "default",
"course" varchar(255) COLLATE "default"
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Records of T_STUDENT
-- ----------------------------
INSERT INTO "public"."T_STUDENT" VALUES ('1', '李四', '12,45,1,66,7,89');
INSERT INTO "public"."T_STUDENT" VALUES ('2', '刘一', '1,5,8,9');
INSERT INTO "public"."T_STUDENT" VALUES ('3', '王五', '0,4,2');
INSERT INTO "public"."T_STUDENT" VALUES ('4', '张三', '1,2,5,7');
-- ----------------------------
-- Alter Sequences Owned By
-- ----------------------------
-- ----------------------------
-- Table structure for T_STUDENT
-- ----------------------------
DROP TABLE IF EXISTS "public"."T_STUDENT";
CREATE TABLE "public"."T_STUDENT" (
"id" int4,
"name" varchar(255) COLLATE "default",
"course" varchar(255) COLLATE "default"
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Records of T_STUDENT
-- ----------------------------
INSERT INTO "public"."T_STUDENT" VALUES ('1', '李四', '12,45,1,66,7,89');
INSERT INTO "public"."T_STUDENT" VALUES ('2', '刘一', '1,5,8,9');
INSERT INTO "public"."T_STUDENT" VALUES ('3', '王五', '0,4,2');
INSERT INTO "public"."T_STUDENT" VALUES ('4', '张三', '1,2,5,7');
-- ----------------------------
-- Alter Sequences Owned By
-- ----------------------------
id name course
4   张三  1,2,5,7
1   李四  12,45,1,5,66,7,89
2   刘一  1,5,8,9
3   王五  0,4,2
SELECT * FROM "public"."T_STUDENT" WHERE string_to_array(course, ',') @> ARRAY['2','7']
结果:
id name course
4   张三  1,2,5,7
SELECT * FROM "public"."T_STUDENT" WHERE string_to_array(course, ',') <@ array['5','12','45','1','0','4','2']
结果:
id name course
3   王五  0,4,2
SELECT * FROM "public"."T_STUDENT" WHERE string_to_array(course, ',') && ARRAY['5','8','225','111']
结果:
id name course
4   张三  1,2,5,7
2   刘一  1,5,8,9

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/dbsjack/article/details/80745922