[英]H2 Database: Get rows from subquery as array
我有一个在 PostgreSQL 上运行良好的查询,我需要在 H2Database 上使用它。
对表来说重要的是基本上只有一个id integer
字段。
带有结果的 PostgreSQL 示例查询在这里:
select id,
array_to_string(
array(select id from table1)
,',')
from table2
order by id
结果:
id | array_to_string
2 | 1,3,4,5,2
3 | 1,3,4,5,2
4 | 1,3,4,5,2
6 | 1,3,4,5,2
7 | 1,3,4,5,2
8 | 1,3,4,5,2
9 | 1,3,4,5,2
10 | 1,3,4,5,2
对于 H2,我实现了用户定义的函数array_to_string
和array
,如下所示:
public class H2Functions {
public static String arrayToString(final Object[] array, final String separator) {
return StringUtils.join(array, separator);
}
public static Object array(final Object row) {
return "???";
}
}
问题是我无法实现array
因为我不知道它传递了什么。
查询失败:
Scalar subquery contains more than one row;
我怎样才能说服 H2 返回array
可以使用的东西?
您并不真的希望行作为数组,而是希望它们作为逗号分隔的列表。 而array_to_string( array(select id from table1),',')
在 Postgres 中是不必要的复杂。 可以简化为
select id,
(select string_agg(id::text, ',') from table1) as id_list
from table2
order by id
这清楚地表明您可以简单地使用 H2 的group_concat()
,它相当于 Postgres 的string_agg()
:
select id,
(select group_concat(id separator ',') from table1) as id_list
from table2
order by id
由于 1.4.197 H2 vervion 也将值聚合到数组中,函数 ARRAY_AGG 可用。
见https://www.h2database.com/html/functions-aggregate.html#array_agg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.