如何更新'postgresql'中'where'搜索的数组中的元素?

时间:2016-01-27 13:31:02

标签: postgresql

CREATE TABLE tlps
(
  id integer NOT NULL,
  telephone telephone[],
  CONSTRAINT tlps_pkey PRIMARY KEY (id)
)

CREATE TYPE telephone AS
   (phone_code integer,
    number character varying(9)
)

我想将电话[]中的电话666666666更新为600000000

1 个答案:

答案 0 :(得分:1)

使用array_replace()

localhost:2345

案例 - 列insert into tlps values (1, array['123456789', '666666666']); update tlps set telephone = array_replace(telephone, '666666666', '600000000') where id = 1; select * from tlps; id | telephone ----+----------------------- 1 | {123456789,600000000} (1 row) 属于复合类型:

telephone

对于给定create type telephone as (phone_code integer, number character varying(9)); insert into tlps values (1, array[(1,'123456789'), (2,'666666666')]::telephone[]); 的简单更新phone (2, '666666666')phone (2, '600000000')

id

找到电话号码update tlps set telephone = array_replace(telephone, (2,'666666666')::telephone, (2,'600000000')::telephone) where id = 1; 并将其替换为'123456789'(我们不知道'111222333'也不会phone_code):

id
不过,我不喜欢将电话号码存储在如此复杂的结构中的想法,也不知道它是为什么发明的。