我有一个表,它有一个名为tags的字段,可以包含任意数量的字符串:
Table "public.page"
Column | Type | Modifiers
----------------------+--------------------------+----------------------------------
tags | text[] | not null default ARRAY[]::text[]
我想在标签字段中添加一个字符串,但我似乎无法让concat函数为我工作
update page set tags=concat('My New String',tags);
ERROR: function concat(unknown, text[]) does not exist
LINE 1: update page set tags=concat('My New String',tags) where ...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
和
update page set tags=('My New String'||tags);
ERROR: operator is not unique: unknown || text[]
LINE 1: update page set tags = ('My New String' || tags) where w...
^
HINT: Could not choose a best candidate operator. You might need to add explicit type casts.
有什么想法吗?
在PostgreSQL的类型系统中,文本'My New String'
不是varchar
或text
值,而是unknown
类型的文本,可以作为任何类型处理。(例如,date
的文字可能是'2013-08-29'
;这不会被处理为varchar
,然后转换为date
,它会被解释为非常低级别的"date
文字"。)
通常,PostgreSQL可以自动推导类型,但当它不能时,您需要使用以下其中一个来告诉它,您希望将文字处理为text
:
text 'My New String'
(SQL标准文本语法)Cast('My New String' as text)
(SQL标准强制转换语法,但在此上下文中不是真正的强制转换)'My New String'::text
(PostgreSQL非标准转换语法,但可读性很强)
在您的案例中,错误消息operator is not unique: unknown || text[]
表示Postgres可以将文本解释为多种类型,每种类型都有自己的||
运算符定义。
因此,您需要这样的东西(我删除了不必要的括号):
update page set tags = 'My New String'::text || tags;
是否尝试||
进行连接?
select array['abc','def']::text[] || 'qwerty'::text;
http://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-操作员表
注:此回答是对OP的原始(未经编辑)问题的回应。其他答案包含与更新问题相关的更多细节。