PostgreSQL 对数组字段增删改查
PostgreSQL About 1,277 words增
添加一个元素
例:向文章标签字段尾部添加abc这个标签。
update post set topics = array_append(topics, 'abc') where id = 1;
例:向文章标签字段头部添加abc这个标签。
update post set topics = array_prepend(topics, 'abc') where id = 1;
添加多个元素
例:向文章标签字段中添加abc和edf标签数组。
update post set topics = array_cat(topics, ARRAY['abc','edf']) where id = 1;
删
删除一个元素
例:删除文章标签字段中的abc这个标签。
update post set topics = array_remove(topics, 'abc') where id = 1;
改
替换某个元素
例:替换文章标签字段中的abc字段为def。
update post set topics = array_replace(topics, 'abc', 'def') where id = 1;
查
是否包含某个元素
例:查询文章表中topics字段包含abc这个标签的所有文章。
select * from post where 'abc'=ANY(topics);
查询数组长度
例:查询文章表中topics字段的标签数量(第二个参数1表示一维数组的长度,以此递推)。
select array_length(topics, 1) from post where id = 1;
例:查询文章表中topics字段的所有维度的标签数量(多维数组中的数组也累加计数)。
select cardinality(topics) from post where id = 1;
特定连接符连接且以字符串形式返回
例:文章表中的topics字段以,连接(数组中有元素为NULL,则忽略该元素)。
select array_to_string(topics, ',') from post where id =1;
-- MySQL,Oracle
例:文章表中的topics字段以,连接,*表示替换NULL元素显示。
select array_to_string(topics, ',', '*') from post where id =1;
-- MySQL,*,Oracle
函数总结
array_append:向数组尾部添加元素;array_prepend:向数组头部添加元素;array_cat:拼接两个数组;array_remove:删除某个元素;array_replace:替换某个元素;'xxx'=ANY(topics):是否包含某个元素;array_length:返回指定维度数组的元素数量;cardinality:返回所有维度数组的元素数量;array_to_string:数组以特定连接符连接并且以字符串形式返回;
Views: 7,795 · Posted: 2020-03-22
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...