我如何使用别名与子句?

发布于 2025-01-31 02:50:21 字数 994 浏览 6 评论 0原文

我试图将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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掩饰不了的爱 2025-02-07 02:50:21

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 the HAVING clause, then make your query a native one, and it will run without any problems assuming MySQL be the underlying database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文