3

我有一个表,其中包含一个名为 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.

有任何想法吗?

4

2 回答 2

9

在 PostgreSQL 的类型系统中,字面'My New String'量不是一个varcharortext值,而是一个 type 的字面量unknown,可以作为任何类型处理。(例如, a 的文字date可以是'2013-08-29'; 这不会被处理为 avarchar然后转换为,它会在非常低的级别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;
于 2013-08-29T16:17:40.593 回答
0

您是否尝试||连接?

select array['abc','def']::text[] || 'qwerty'::text;

http://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-OPERATORS-TABLE

注意:此答案是对 OP 的原始(未经编辑)问题的回应。其他答案包含与更新问题相关的更多详细信息。

于 2013-08-29T16:10:09.630 回答