[英]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.