sql - 如何连接 Postgres SELECT 中的列?

标签 sql postgresql types concatenation coalesce

我在表 foo 中有两个字符串列 ab

select a, b from foo 返回值 ab。但是,ab 的连接不起作用。我试过了:

select a || b from foo

select  a||', '||b from foo

根据评论更新:两列都是 character(2) 类型。

最佳答案

string typecharacter(2) 这样的列(正如您稍后提到的那样),显示的串联才有效,因为 quoting the manual:

[...] the string concatenation operator (||) accepts non-string input, so long as at least one input is of a string type, as shown in Table 9.8. For other cases, insert an explicit coercion to text [...]

大胆强调我的。第二个示例(select a||', '||b from foo)适用于任何数据类型,因为未类型化的字符串文字', ' 默认输入 text 使整个表达式在任何情况下都有效。

对于非字符串数据类型,您可以通过 casting“修复”第一条语句text 的至少一个参数。 (任何类型都可以转换为text):

SELECT a::text || b AS ab FROM foo;

your own answer来看,“不起作用”应该意味着“返回 NULL”。 anything 连接到 NULL 的结果是 NULL。如果可以包含NULL值且结果不应该为NULL,则使用concat_ws()连接任意数量的值(Postgres 9.1 或更高版本):

SELECT concat_ws(', ', a, b) AS ab FROM foo;

分隔符仅在非空值之间添加,即仅在必要时添加。

concat() 如果您不需要分隔符:

SELECT concat(a, b) AS ab FROM foo;

这里不需要类型转换,因为两个函数都采用 "any"输入和处理文本表示。

此相关答案中的更多详细信息(以及为什么 COALESCE 是一个糟糕的替代品):

关于 comment 中的更新

+ 不是 Postgres(或标准 SQL)中字符串连接的有效运算符。将此添加到他们的产品中是 Microsoft 的私有(private)想法。

几乎没有什么好的理由使用character(n)(同义词:char(n) ).使用 text or varchar .详情:

关于sql - 如何连接 Postgres SELECT 中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19942824/

相关文章:

mysql - 如何选择 mycolumn 为整数值的所有行?

postgresql - 使用 Testcontainers 时如何设置 Postgresql 的端口?

postgresql - Postgres - 选择日期列值在另一行值范围内的所有行?

json - 嵌套的 JSON golang 映射

java - 使用 Hibernate 映射 boolean[] PostgreSql 列

mysql - 如何更新 mysql 查询中的列

php - 在 mysql 中得到错误的结果?

sql - 如何在 Postgres 中进行昵称搜索

java - 在 MATLAB 中读取文件时指定数据类型

mysql - 如何在Mysql中检索三或四个表的交集