ORDER BY 与 LIMIT 和 MySQL

Jin*_*xen 3 java mysql sql jpql

我在使用 MySQL 查询时遇到问题,我得到一行 LIMIT 1。但是当它与 order by 一起使用时,它不起作用。

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

select * from train t 
where t.togId = 1125 
and t.tilDato >= '2013-12-20' 
order by t.fraDato LIMIT 1; 
Run Code Online (Sandbox Code Playgroud)

但是,当我通过 javacode 并在我的服务器上运行它时,我得到了这个堆栈跟踪:

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.
Run Code Online (Sandbox Code Playgroud)

查询是这样创建的:

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());
Run Code Online (Sandbox Code Playgroud)

hor*_*rec 5

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

所以,而不是LIMIT 1你应该使用

query.setMaxResults(1);
Run Code Online (Sandbox Code Playgroud)