PostgreSQL 对数组字段的简单操作

479 阅读1分钟

t1表

idtags
1{1,2,3,test}

相关函数

  • array_append:向数组尾部添加元素;
  • array_cat:拼接两个数组;
  • array_remove:删除某个元素;
  • array_replace:替换某个元素;
  • tags @> '{test}':是否包含某个元素;
  • array_to_string:数组以特定连接符连接并且以字符串形式返回;

函数简单应用

select tags,  #执行结果: {1,2,3,test}
       array_append(tags, '9') as array_append, #执行结果: {1,2,3,test,9}
       array_cat(tags, tags) as array_cat, #执行结果: {1,2,3,test,1,2,3,test}
       array_remove(tags, 'test'), #执行结果: {1,2,3}
       array_replace(tags, 'test', 'TEST'), #执行结果: {1,2,3,TEST}
       tags @> '{test}', #执行结果: true
       array_to_string(tags, ',') #执行结果: 1,2,3,TEST
from t1 where id = 1;

添加元素

update t1 set tags = array_append(tags, '9') where id = 1

添加元素(如果存在则不添加)

update t1 set tags = array_append(tags, '9') where id = 1 and (tags @> '{test}' = false)

移除元素

update t1 set tags = array_remove(tags, '9') where id = 1

替换元素

update t1 set tags = array_replace(tags, '9') where id = 1

查找是否存在

select tags @> '{test}' from t1 where id = 1