数据库
首页 > 数据库> > java-使用LIMIT和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