Count(*) 在另一个 count(*) 中
Count(*) inside another count(*)
首先,很抱歉,如果这个问题已经被问到,但我在搜索时找不到任何东西。
我是 Hibernate 的新手,我不确定这是否可以完成,但我正在尝试将以下查询从 SQL 转换为 Hibernate:
Select count(*) from (
Select count(*)
from table
where field1 in (...)
Group by field1, field2);
现在,我知道我可以获得第二个查询的列表并检查其大小,但我想使用 uniqueResult() 方法来执行此操作,因为它更有效。
关于如何做到这一点有什么想法吗?
提前致谢!
编辑 1:对不起,我忘了说我正试图用 HQL 来做这件事。
Hibernate 子查询中的 from
子句。您可以通过将查询重写为计算 field1
和 field2
的不同连接来解决此问题,正如@sagi 在评论中已经建议的那样,或者,如果您发现连接成本太高,则为:
select count(*) from table
where id in
(select max(id) from table
where field1 in (...)
group by field1, field2);
如果你能做到就好了:
Select count(distinct field1, field2)
from table
where field1 in (...)
但我认为这在 Hibernate 中不起作用。一种解决方法是将值(如 Sagi 在评论中提到的那样)与分隔符连接起来:
Select count(distinct field1 || ':' || field2)
from table
where field1 in (...);
请注意:此版本将以不同于原始查询的方式处理 NULL
值。这很容易处理,但会使逻辑稍微复杂一些。
首先,很抱歉,如果这个问题已经被问到,但我在搜索时找不到任何东西。
我是 Hibernate 的新手,我不确定这是否可以完成,但我正在尝试将以下查询从 SQL 转换为 Hibernate:
Select count(*) from (
Select count(*)
from table
where field1 in (...)
Group by field1, field2);
现在,我知道我可以获得第二个查询的列表并检查其大小,但我想使用 uniqueResult() 方法来执行此操作,因为它更有效。
关于如何做到这一点有什么想法吗? 提前致谢!
编辑 1:对不起,我忘了说我正试图用 HQL 来做这件事。
Hibernate from
子句。您可以通过将查询重写为计算 field1
和 field2
的不同连接来解决此问题,正如@sagi 在评论中已经建议的那样,或者,如果您发现连接成本太高,则为:
select count(*) from table
where id in
(select max(id) from table
where field1 in (...)
group by field1, field2);
如果你能做到就好了:
Select count(distinct field1, field2)
from table
where field1 in (...)
但我认为这在 Hibernate 中不起作用。一种解决方法是将值(如 Sagi 在评论中提到的那样)与分隔符连接起来:
Select count(distinct field1 || ':' || field2)
from table
where field1 in (...);
请注意:此版本将以不同于原始查询的方式处理 NULL
值。这很容易处理,但会使逻辑稍微复杂一些。