查询在两个日期之间搜索

时间:2013-12-06 13:02:21

标签: mysql sql jpql

大家好我有一个搜索查询,应该显示设定日期范围之间的所有结果

查询:

public List<Appointment> appointmentRangeSearch(Date startdatetime, Date endDate) {
    Query q = em.createQuery("SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN : date1 AND : date2 ");
    q.setParameter("date1", startdatetime, TemporalType.TIMESTAMP);
    q.setParameter("date2", endDate, TemporalType.TIMESTAMP);
    return q.getResultList();
}

它正在返回错误:

Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing [SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN : date1 AND : date2 ]. 
[34, 77] The expression is not a valid conditional expression.

表中的数据已存储:

2013-12-15 00:00:00.0

我该如何完成此搜索?

谢谢你们

2 个答案:

答案 0 :(得分:1)

:移除date1: date1之间的空格。所以你的查询应该是这样的:

SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN :date1 AND :date2

答案 1 :(得分:1)

您的语法错误已解决,但您可能遇到与您的问题无关的逻辑问题。如果您的数据类型是datetime,并且数据包含时间部分,那么:

where myField between '2013-12-01' and '2013-12-05'

不会选择包含2013-12-05 01:00

等值的记录

解决方案就是这样做

where myField >= '2013-12-01'
and myField < '2013-12-06' -- note that this is one day later