【发布时间】:2018-10-05 16:01:35
【问题描述】:
假设您有一个 SELECT id from table 查询(实际情况是一个复杂的查询),它确实会返回多个结果。
问题是如何让所有id在一行中返回,逗号分隔?
【问题讨论】:
-
上述“欺骗”是相关且有用的,尤其是
array_agg()函数。
标签: sql postgresql
假设您有一个 SELECT id from table 查询(实际情况是一个复杂的查询),它确实会返回多个结果。
问题是如何让所有id在一行中返回,逗号分隔?
【问题讨论】:
array_agg() 函数。
标签: sql postgresql
您可以使用 array() 和 array_to_string() 函数来处理您的查询。
使用SELECT array( SELECT id FROM table );,您将获得如下结果:{1,2,3,4,5,6}
然后,如果您想删除 {} 符号,您可以使用 array_to_string() 函数并使用逗号作为分隔符,因此:SELECT array_to_string( array( SELECT id FROM table ), ',' ) 将得到如下结果:1,2,3,4,5 ,6
【讨论】:
SELECT array_to_string( id, ',' ) AS id FROM table
SELECT string_agg(id::text, ',') FROM table
需要 PostgreSQL 9.0,但这不是问题。
【讨论】:
string_agg(CAST(id as varchar), ',')。
string_agg(id::text, ',')
select string_agg(id, ', ' order by id desc) from table
STRING_AGG(DISTINCT customer_name, ',')解决了它
您可以使用 psql 从任何 SQL 查询生成 CSV:
$ psql
> \o myfile.csv
> \f ','
> \a
> SELECT col1 AS column1, col2 AS column2 ... FROM ...
生成的 myfile.csv 将 SQL 结果集列名作为 CSV 列标题,将查询元组作为 CSV 行。
h/thttp://pookey.co.uk/wordpress/archives/51-outputting-from-postgres-to-csv
【讨论】:
使用 array_to_string() & array() 函数。
select array_to_string(array(select column_name from table_name where id=5), ', ');
【讨论】:
string_agg() 更好吗?
SELECT array_agg(id, ',') FROM table
{1,2,3,4}
我正在使用 Postgres 11,而 EntityFramework 将其作为整数数组获取。
【讨论】:
使用下面的查询它将起作用并给出确切的结果。
SELECT array_to_string(array_agg(id), ',') FROM table
输出:{1,2,3,4,5}
【讨论】: