【问题标题】:ORDER BY with LIMIT and MySQLORDER BY 与 LIMIT 和 MySQL
【发布时间】:2014-01-09 08:56:52
【问题描述】:

我在使用 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; 

但是,当我通过 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.

查询是这样创建的:

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());

【问题讨论】:

  • select *替换select t
  • 也可以SELECT t.*.
  • 在您的工作台查询中选择 *.您的 java 代码已选择 t。除非您的火车表有一个名为 t 的列,否则您将收到某种错误。

标签: java mysql sql jpql


【解决方案1】:

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

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

query.setMaxResults(1);

【讨论】:

    【解决方案2】:

    使用query.setMaxResults() 而不是Limit 将无法与hql 一起使用

    Query q = session.createQuery("FROM table");
    q.setFirstResult(start);
    q.setMaxResults(maxRows);
    

    请参阅下面发布在 hibernate 论坛中的链接

    https://forum.hibernate.org/viewtopic.php?f=9&t=939314

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多