我如何使用别名与子句?
我试图将JPQL等效于以下SQL。
SELECT last_name, COUNT(1) AS c
FROM actor
GROUP BY last_name
HAVING c > 1
ORDER BY c DESC
我尝试了以下JPQL。
SELECT e.lastName, COUNT(e.lastName) AS c
FROM Actor
GROUP BY e.lastName
HAVING c > 1
ORDER BY c DESC
Hibernate会产生SQL之后并投诉。
select
actor0_.last_name as col_0_0_,
count(actor0_.last_name) as col_1_0_
from
actor actor0_
group by
actor0_.last_name
having
c>=?
order by
col_1_0_ DESC limit ?
当我这样更改JPQL时,它可以正常工作。
SELECT e.lastName, COUNT(e.lastName) AS c
FROM Actor
GROUP BY e.lastName
HAVING COUNT(e.lastName) > 1
ORDER BY c DESC
我如何将名为c
的别名与子句一起使用?
如果我不能,查询还可以吗?有什么最佳方法吗?
谢谢。
I'm trying to JPQL equivalent to the following SQL.
SELECT last_name, COUNT(1) AS c
FROM actor
GROUP BY last_name
HAVING c > 1
ORDER BY c DESC
I tried with the following JPQL.
SELECT e.lastName, COUNT(e.lastName) AS c
FROM Actor
GROUP BY e.lastName
HAVING c > 1
ORDER BY c DESC
And Hibernate generates following SQL and complains.
select
actor0_.last_name as col_0_0_,
count(actor0_.last_name) as col_1_0_
from
actor actor0_
group by
actor0_.last_name
having
c>=?
order by
col_1_0_ DESC limit ?
When I changed the JPQL like this, it works.
SELECT e.lastName, COUNT(e.lastName) AS c
FROM Actor
GROUP BY e.lastName
HAVING COUNT(e.lastName) > 1
ORDER BY c DESC
How can I use the alias named c
with the HAVING
clause?
If I just can not, is the query ok? any optimal way to do that?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JPQL不支持使用子句中的别名,主要是因为并非所有SQL引擎都支持此行为。例如,Oracle和Postgres都不支持您的第一个查询版本。
如果要使用纯JPQL,则只需在具有子句的
中重复整个计数表达式即可。如果您确实想在具有
子句中的中重复使用别名,则将您的查询作为本机,并且假设MySQL是基础数据库而不会有任何问题。
JPQL does not support using the alias in the
HAVING
clause, mainly because not all SQL engines support this behavior. For example, both Oracle and Postgres would not support your first version of the query.If you want to use pure JPQL, then just repeat the entire count expression in the
HAVING
clause. If you really want to reuse the alias in theHAVING
clause, then make your query a native one, and it will run without any problems assuming MySQL be the underlying database.