欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > 数据库 >内容正文

数据库

java mysql order by,java-使用LIMIT和MySQL进行ORDER BY

发布时间:2024/9/27 数据库 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java mysql order by,java-使用LIMIT和MySQL进行ORDER BY 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我在使用MySQL查询时遇到问题,在该查询中我得到了一个带有LIMIT 1的行.但是,将其与order一起使用时,它不起作用.

在mysql工作台中运行的查询如下:

select * from train t

where t.togId = 1125

and t.tilDato >= '2013-12-20'

order by t.fraDato LIMIT 1;

但是,当我通过javacode和在我的服务器上运行此消息时,得到此stacktrace:

Exception Description:

Syntax error parsing [select t from train t where t.togId = :togId

and t.tilDato >= :todaysdate order by t.fraDato LIMIT 1].

[102, 103] The ORDER BY clause has 't.fraDato ' and 'LIMIT '

that are not separated by a comma.

[108, 109] The ORDER BY clause has 'LIMIT ' and '1' that are not separated by a comma.

查询是这样创建的:

Query query = em.createQuery("select t from train t where t.togId = :togId" +

" and t.tilDato >= :todaysdate order by t.fraDato LIMIT 1")

.setParameter("togId", togId)

.setParameter("todaysdate", new Date());

解决方法:

您似乎正在使用JPQL,即Java持久性查询语言. MySQL和JPQL(或Hibernate)是完全不同的查询语言,它们每个都有自己的特定语法. LIMIT构造仅在MySQL中可用,并且不属于任何SQL标准.通过在查询对象上设置最大结果数来模拟JPA中的功能.

因此,您应该使用LIMIT 1而不是LIMIT 1

query.setMaxResults(1);

标签:jpql,sql,java,mysql

来源: https://codeday.me/bug/20191030/1964949.html

总结

以上是生活随笔为你收集整理的java mysql order by,java-使用LIMIT和MySQL进行ORDER BY的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。