java 休眠 SELECT DISTINCT 行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26334244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:44:00  来源:igfitidea点击:

Hibernate SELECT DISTINCT behavior

javahibernatehqldistinct

提问by Kirill Reznikov

I hope that this question is not duplicate, because in another case I use google badly (shame on me) :-)

我希望这个问题不是重复的,因为在另一种情况下,我严重使用谷歌(我感到羞耻):-)

So, I can't find exact and clear answer for my question: Is "SELECT DISTINCT ..." in hql applied before setFirstResult() and setMaxResults()? I want to be calm that I will not have problems with pagination in my app.

所以,我找不到我的问题的准确和明确的答案:在 setFirstResult() 和 setMaxResults() 之前是否应用了 hql 中的“SELECT DISTINCT ...”?我想保持冷静,我的应用程序中的分页不会出现问题。

采纳答案by JamesENL

To answer the actual question, yes the distinct result set would be determined before the limit would be applied. The setFirstResult()and setMaxResults()methods essentially are equivalent to a LIMITclause on the query.

要回答实际问题,是的,将在应用限制之前确定不同的结果集。该setFirstResult()setMaxResults()方法实质上是等同于LIMIT在查询子句。

If you use both you are requesting that the distinct result set be limited between the indexes given to your two method calls above.

如果您同时使用两者,则您要求将不同的结果集限制在给定给上述两个方法调用的索引之间。

An example:

一个例子:

You have a result set with 100 records. There are 20 distinct records found for column X. You set up the following criteria:

您有一个包含 100 条记录的结果集。为 X 列找到了 20 个不同的记录。您设置了以下条件:

Criteria critiera = getCurrentSession().createCritiera(Foo.class);
criteria.add(Projections.distinct(Projections.property("X")));
criteria.setFirstResult(0);
criteria.setMaxResults(10);
List<Foo> fooList = critiera.list();

fooListwould contain 10 results, from the start of the distinct result set of 20 results.

fooList将包含 10 个结果,从 20 个结果的不同结果集开始。

If you changed the above to

如果您将上述更改为

criteria.setFirstResult(4);
criteria.setMaxResults(20);

fooListwould contain 15 results omitting the first 5 results.

fooList将包含 15 个结果,省略前 5 个结果。

It could be ambiguous how the result set would be ordered, so you may not get the same 10 results every time.

结果集的排序方式可能不明确,因此您可能不会每次都获得相同的 10 个结果。

回答by chenthil

SELECT DISTINCT

选择不同

When the keyword DISTINCT is used after SELECT, it works as a shortcut replacement for a simple GROUP BY clause. The expressions in the SELECT list are used directly as the . The following examples of SELECT DISTINCT and SELECT with GROUP BY are equivalent. From reference documentation

在 SELECT 之后使用关键字 DISTINCT 时,它可以作为简单 GROUP BY 子句的快捷方式替换。SELECT 列表中的表达式直接用作 . 以下 SELECT DISTINCT 和 SELECT with GROUP BY 示例是等效的。来自参考文档

SELECT DISTINCT d, e + f FROM atable WHERE a + b = c
 SELECT d, e + f FROM atable WHERE a + b = c GROUP BY d, e + f`