gpt4 book ai didi

java - H2数据库: Get rows from subquery as array

转载 作者:行者123 更新时间:2023-11-30 03:05:27 30 4
gpt4 key购买 nike

我有一个可以在 PostgreSQL 上正常运行的查询,并且我需要在 H2Database 上使用它。

对于表来说重要的基本上只是一个 id 整数 字段。

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_stringarray,如下所示:

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

关于java - H2数据库: Get rows from subquery as array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34903917/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com