H2 DB - 如何禁用完整分组

H2 DB - How to disable full group by

mysql 中有一个标志 enable/disable 完整分组依据 (ONLY_FULL_GROUP_BY) 但我正在搜索相同的标志或连接字符串参数以在 H2 数据库中禁用完整分组依据.

这是我的示例数据。

+----+---------------+-----------------+
| ID | SYNC_ID       | LIFECYCLE_EVENT |
+----+---------------+-----------------+
| 3  | 41            | 2               |
+----+---------------+-----------------+
| 2  | 41            | 1               |
+----+---------------+-----------------+
| 4  | 69            | 1               |
+----+---------------+-----------------+
| 5  | 69            | 3               |
+----+---------------+-----------------+

这是我想要的输出:

+----+---------------+-----------------+
| ID | SYNC_ID       | LIFECYCLE_EVENT |
+----+---------------+-----------------+
| 3  | 41            | 2               |
+----+---------------+-----------------+
| 5  | 69            | 3               |
+----+---------------+-----------------+

这是我的查询,我试图将其用于所需的输出

select   id, sync_id, max(lifecycle_event)
from asset
where asset_type = 1
GROUP BY sync_id;

但它给了我 ErrorCode: 90016 这意味着所有非聚合列都应该在分组依据中选择。如果我这样做,我会得到错误的数据结果。

所以很明显我不想按 id 和 sync_id 分组。请指导我如何在 H2 数据库中实现此目的。

几乎所有其他数据库都没有这样的东西 -- 因为 group by 在那些数据库中没有损坏。您可以这样表达查询:

select a.*
from asset a
where asset_type = 1 and
      lifecycle_event = (select max(lifecycle_event) from asset a2 where a2.sync_id = a.sync_id);

你可以试试下面的-

select max(id),sync_id, max(lifecycle_event)
from asset
where asset_type = 1
GROUP BY sync_id

我认为尝试模仿 MySQL 损坏的 group by 实现没有任何意义。

您可以将查询重写为

select a1.id, a1.sync_id, a2.max_even
from asset a1
  join (
    select sync_id,  max(lifecycle_event) as max_event
    from asset 
    group by sync_id
  ) a2 on a2.sync_id = a1.sync_id
      and a2.max_event = a1.lifecycle_event;