【问题标题】:H2 Database: Get rows from subquery as arrayH2 数据库:从子查询中获取行作为数组
【发布时间】:2016-01-20 15:23:12
【问题描述】:

我有一个可以在 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_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 可以使用的东西?

【问题讨论】:

  • 不相关,但是:从table1 中为table2每一 行检索all id 似乎很奇怪对我来说。你确定你不想要一个共同相关的子查询吗?甚至是这些表之间的正确连接和group by
  • 查询只是一个示例查询,在我的应用程序中有子句。

标签: java sql arrays h2


【解决方案1】:

您实际上并不希望将行作为数组,而是希望将它们作为逗号分隔的列表。而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

【讨论】:

    【解决方案2】:

    从 1.4.197 H2 版本开始,也可以将值聚合到数组函数 ARRAY_AGG 中。
    https://www.h2database.com/html/functions-aggregate.html#array_agg

    【讨论】:

      猜你喜欢
      • 2014-03-25
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 2021-06-30
      相关资源
      最近更新 更多