Erw*_*ter 2 postgresql null concat
连接运算符||
可以连接任何字符串类型的值,返回text
. 在 Postgres 中,每种类型都有一个文本表示并且可以转换为text
. 因此,引用手册:
但是,字符串连接运算符 (
||
) 仍然接受非字符串输入,只要至少一个输入是字符串类型
有关的:
连接一个或多个NULL
值产生结果NULL
。
test=# SELECT (text 'foo' || NULL) IS NULL
test-# , (text 'bar' || char '1' || NULL ) IS NULL
test-# , (NULL::bigint || text 'baz') IS NULL;
?column? | ?column? | ?column?
----------+----------+----------
t | t | t
Run Code Online (Sandbox Code Playgroud)
是否可以连接 atext
和 aNULL
值并获得非空结果?
换句话说,这怎么可能?
test=# SELECT col IS NULL AS col_is_null
test-# , (text 'foo' || col) IS NULL AS result_is_null
test-# FROM tbl;
col_is_null | result_is_null
-------------+----------------
t | f
Run Code Online (Sandbox Code Playgroud)
适用于任何 Postgres 版本。
我的一个客户偶然发现了这一点,依靠结果是NULL
,我发现它很有趣,可以分享。
这是一个有点棘手的问题,因为我知道答案。
注意: CASE
或COALESCE
捕获NULL
值通常是很好的风格,但这不是这个问题的内容。它是关于与实际NULL
值的连接,使用连接运算符||
并仍然获得非空结果。
那是因为 PostgreSQL 中的 CASTing 数组类型系统有点奇怪(乍一看):-)
text || text[]
使双方都被强制为数组。
CREATE TABLE tbl (col text ARRAY);
INSERT INTO tbl SELECT NULL;
SELECT col IS NULL AS col_is_null,
(text 'foo' || col) IS NULL AS result_is_null
FROM tbl;
col_is_null | result_is_null
-------------+----------------
t | f
(1 row)
Run Code Online (Sandbox Code Playgroud)
另一个可能更清楚的例子:
create temp table x as select 'foo' test, null::text[] col;
SELECT test, col, test || col from x;
test | col | ?column?
------+------+----------
foo | NULL | {foo}
(1 row)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1171 次 |
最近记录: |