在日期范围,INCLUSIVE之间查询

时间:2014-08-11 16:43:27

标签: php mysql datetime timestamp

我有一个名为CREATED的TIMESTAMP列。我试图让两个时间戳之间的所有行包含INCLUSIVE。这是有效的(独家):

select id, created 
  from employees 
 where created < '08/11/2014 00:00:01' 
   and created > '08/08/2014 00:00:01' 
 order by created desc;

但这不是:

select id, created 
  from employees 
 where created <= '08/11/2014 00:00:01' 
   and created => '08/08/2014 00:00:01'
 order by created desc;

为什么MySQL没有识别=&lt;和&gt; =这种情况下的符号?

4 个答案:

答案 0 :(得分:2)

您正在寻找的运营商是>=<=。我相信您正在使用=<

要将TIMESTAMP或DATETIME表示为字符串,您必须使用YYYY-MM-DD。您正在使用MM/DD/YYYY。这将无法正常工作。

请注意,如果要选择在特定日期范围内出现的TIMESTAMP值,最好的方法是使用此类查询。这将从8月8日,9日,10日的任何时间获得带有时间戳的项目。

select id, created 
  from employees 
 where created >= '2014-08-08'
   and created <  '2014-08-10' + INTERVAL 1 DAY 
 order by created desc;

范围的结尾(created < '2014-08-10' + INTERVAL 1 DAY)将所有内容都包含在内,但不包括在您想要的范围的最后一天午夜。

你所拥有的是午夜后的一秒钟。如果您的某些记录没有任何时间,只有日期,这可能会让您感到困惑。如果您有一条记录,例如日期为2014-08-08而没有指定任何时间,那么您的00:01查询将无法提取。

答案 1 :(得分:0)

您必须使用以下语法:&gt; =或&lt; =。

答案 2 :(得分:0)

=>是非法运营商。如果尝试使用它,将会出现语法错误。使用>=<=表示大于或等于,小于或等于。

另外,日期的正确格式是使用-表示年,月和日之间的分隔符,而不是/

BETWEEN关键字包含在内:

select id, created 
  from employees 
 where created BETWEEN '2014-08-08 00:00:01' AND '2014-08-11 00:00:01'
 order by created desc;

使用BETWEEN时,请务必先将较低的值放入。

答案 3 :(得分:0)

还有另一种方法:在源字段上使用 CAST()。

select id, created 
  from employees 
 where CAST(created as DATE) <= '08/11/2014' 
   and CAST(created as DATE) >= '08/08/2014' 
 order by created desc;

更好:

select id, created 
  from employees 
 where CAST(created as DATE) BETWEEN '08/11/2014'
   and '08/08/2014' 
 order by created desc;

这将时间排除在比较之外并且可以很好地满足您的目的。