我有一个包含几个字段的表。一个字段是 char[128]
。现在我在那里存储了一个字符串 'hello'
。
现在。在 PHP 中,我调用:arr = pg_fetch_array(pg_query('select * from table'))
但是当我从此列中获取值时,我得到了 'hello '
。当我使用 pgAdmin 执行 'select char_length(this_field) from table'
时,我得到值 5 而不是 6。你知道为什么 PHP 中那里有一个额外的空间吗?
使用 VARCHAR
代替 CHAR
可以解决这个问题。
最佳答案
填充到长度已记录:
https://www.postgresql.org/docs/current/static/datatype-character.html
character(n), char(n) fixed-length, blank padded
例子:
t=# with c(t) as (values('abc'::char(3)),('a'::char(3)))
select t,concat(t,'.') from c;
t | concat
-----+--------
abc | abc.
a | a .
(2 rows)
关于长度:
t=# with c(t) as (values('abc'::char(3)),('a'::char(3)))
select t,concat(t,'.'),octet_length(t),char_length(t) from c;
t | concat | octet_length | char_length
-----+--------+--------------+-------------
abc | abc. | 3 | 3
a | a . | 3 | 1
(2 rows)
使用 character varying
或 text
确实改变了这种行为。
关于sql - PostgreSQL 和 PHP。从查询中获取会增加 char 字符串的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374623/