查询在H2中的group by正常工作,但在Oracle DB中不起作用。

huangapple go评论113阅读模式
英文:

Query group by in h2 works but not in Oracle DB

问题

  1. 我有一个类似以下的查询:
  2. SELECT
  3. sum(field1) as t1.sum_f1,
  4. (select count(*) from table2) as count_t2,
  5. t1.f2
  6. FROM
  7. t1
  8. GROUP BY
  9. t1.f2
  10. 这个查询是由javax.persistence.EntityManager Java实例执行的。
  11. EntityManager将查询在Oracle数据库中运行。
  12. 我编写了使用H2内存数据库配置的Mockito测试。
  13. 问题如下:
  14. 当相同的查询由Mockito测试(使用H2作为数据库)执行时,它正常工作。
  15. 当我运行使用OracleDB作为数据库的Java应用程序时,它给我返回错误:ORA-00979
  16. 我认为它希望在分组字段列表中包含count_t2,但这是不允许的,因为内部查询在分组之后处理(因此count_t2SQL中的“分组时”不可见)。
  17. 我该如何解决?
  18. 谢谢。
英文:

i have a query like the following:

  1. SELECT
  2. sum(field1) as t1.sum_f1,
  3. (select count(*) from table2) as count_t2,
  4. t1.f2
  5. FROM
  6. t1
  7. GROUP BY
  8. t1.f2

This query is getting executed by a javax.persistence.EntityManager java istance.
EntityManager runs the query in an Oracle DB.
I've written Mockito test, configured with H2 in memory database.

The problem is the following:
When the same query is getting executed by a Mockito test (that uses H2 as DB), it works fine.
When i run my java application (that uses OracleDB as DB) it gives me ERROR: ORA-00979.

I think it expects count_t2 to be in the group by field list but this is not permitted cause inner queries are processed after gruop by (so count_t2 is not visible at "group by - time") in SQL.

How can i solve it?
Thanks.

答案1

得分: 1

将计算移到“FROM”子句:

  1. SELECT SUM(field1) as t1.sum_f1, t2.count_t2, t1.f2
  2. FROM t1 CROSS JOIN
  3. (SELECT COUNT(*) as count_t2 FROM table2) t2
  4. GROUP BY t1.f2, t2.count_t2;

具有聚合查询的子查询可能对查询解析器造成困扰。

英文:

Move the calculation to the FROM clause:

  1. SELECT SUM(field1) as t1.sum_f1, t2.count_t2, t1.f2
  2. FROM t1 CROSS JOIN
  3. (SELECT COUNT(*) as count_t2 FROM table2) t2
  4. GROUP BY t1.f2, t2.count_t2;

Subqueries with aggregation queries can be tricky for query parsers.

答案2

得分: 0

我终于找到了让它工作的方法。

  1. 选择
  2. 求和(field1) 作为 t1.sum_f1
  3. 计数((选择 1 table2)) 作为 count_t2
  4. t1.f2
  5. t1
  6. 分组依据
  7. t1.f2

通过这种方式,投影字段为 "SUM, COUNT" 和聚合字段。
这个查询在 H2 和 ORACLE 数据库中都正常工作。

英文:

I finally found the way to let it works.

  1. SELECT
  2. sum(field1) as t1.sum_f1,
  3. count((select 1 from table2)) as count_t2,
  4. t1.f2
  5. FROM
  6. t1
  7. GROUP BY
  8. t1.f2

In this way projection fields are "SUM, COUNT" and the aggregation field.
This query works fine in both H2 and ORACLE DB.

huangapple
  • 本文由 发表于 2020年5月19日 19:59:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61890532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定