[英]H2 Database: Get rows from subquery as array
I have a query which works fine with PostgreSQL, and I need to use it on H2Database.我有一个在 PostgreSQL 上运行良好的查询,我需要在 H2Database 上使用它。
Important for the tables is basically only an id integer
field.对表来说重要的是基本上只有一个
id integer
字段。
The example-query on PostgreSQL with the result is here:带有结果的 PostgreSQL 示例查询在这里:
select id,
array_to_string(
array(select id from table1)
,',')
from table2
order by id
Result:结果:
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
For H2, I implemented the user-defined functions array_to_string
and array
as follows:对于 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 "???";
}
}
The problem is that I can not implement array
as I don't know what it get's passed.问题是我无法实现
array
因为我不知道它传递了什么。
The query fails with:查询失败:
Scalar subquery contains more than one row;
How can I convince H2 to return something which array
can work with ?我怎样才能说服 H2 返回
array
可以使用的东西?
You don't really want the rows as an array, you want them as a comma separated list.您并不真的希望行作为数组,而是希望它们作为逗号分隔的列表。 And
array_to_string( array(select id from table1),',')
is needlessly complicated in Postgres to begin with.而
array_to_string( array(select id from table1),',')
在 Postgres 中是不必要的复杂。 It can be simplified to可以简化为
select id,
(select string_agg(id::text, ',') from table1) as id_list
from table2
order by id
And this makes clear that you can simply use H2's group_concat()
which is the equivalent to Postgres' string_agg()
:这清楚地表明您可以简单地使用 H2 的
group_concat()
,它相当于 Postgres 的string_agg()
:
select id,
(select group_concat(id separator ',') from table1) as id_list
from table2
order by id
Since 1.4.197 H2 vervion also aggregate the value into an array function ARRAY_AGG is available.由于 1.4.197 H2 vervion 也将值聚合到数组中,函数 ARRAY_AGG 可用。
See https://www.h2database.com/html/functions-aggregate.html#array_agg见https://www.h2database.com/html/functions-aggregate.html#array_agg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.