简体   繁体   English

日期(年,月,日)的匹配值,但时间不匹配

[英]Matching value on date (year, month, day) but not time

In this answer , it's suggested to use teh following syntax for matching against a given date, all day long. 此答案中 ,建议整天使用以下语法与给定日期进行匹配。

select * from Info
  where DateColumn 
    between '2014-08-25 00:00:00' 
    and '2014-08-25 23:59:59'

Besides the fact that we're missing the last second of each day, which practically perhaps isn't a large issue but principally might be a deal-breaker, I don't see why not use the simple expression below. 除了我们错过了每天的最后一秒,这实际上不是一个大问题,但主要可能是一个破坏交易的事实,我不明白为什么不使用下面的简单表达式。

The matching is done with on a semi-open interval with the upper bound being exclusive (ie fromAndInclusive <= date < toButNotInclusive ) and a date without any time specified is assumed to be at midnight (ie 00:00:00.000). 匹配是在半开放时间间隔内完成的,上限是互斥的(即fromAndInclusive <= date <toButNotInclusive ),并且没有指定任何时间的日期被假定为午夜(即00:00:00.000)。

select * from Info
  where DateColumn 
    between '2014-08-25' and '2014-08-26'

Please note that I'm not even close to be claiming any level of competence when it comes to SQL so this question shouldn't be been as pointing out any errors. 请注意,在SQL方面,我甚至还没有声称自己具备任何能力,因此,这个问题不应被视为指出任何错误。 I'm cocky otherwise but when it comes to DBs, I've been humbled once or twice. 否则我很自大,但是当涉及到DB时,我一直感到一两次卑鄙。 :) :)

Both will return incorrect results. 两者都将返回不正确的结果。

Between is inclusive at both ends so your first query 包容两个端头,这样你的第一个查询

select * from Info
  where DateColumn 
  between '2014-08-25 00:00:00' 
  and '2014-08-25 23:59:59'

will ignore anything in the last second of 2014-08-25 as you point out. 如您所指出的,它将在2014-08-25的最后一秒忽略任何内容。

The second query you propose is too greedy. 您提出的第二个查询过于贪婪。 It will include anything at exactly midnight on the 26th ie 2014-08-26 00:00:00 . 它将在26号午夜正好包含任何内容,即2014-08-26 00:00:00

select * from Info
  where DateColumn 
  between '2014-08-25' and '2014-08-26'

To get the results you need you should use >= and < (as @Lamak) points out in the comments: 为了获得所需的结果,您应该使用>=< (如@Lamak)在注释中指出:

select * from Info
  where DateColumn >= '2014-08-25' and DateColumn < '2014-08-26'.

Given the following data in the table: 鉴于表中的以下数据:

2014-08-25 23:59:59
2014-08-25 23:59:59.500
2014-08-26 00:00:00
2014-08-26 00:00:00.500
2014-08-26 00:00:01

The first query matches just: 第一个查询仅匹配:

2014-08-25 23:59:59.000

The second matches: 第二场比赛:

2014-08-25 23:59:59.000
2014-08-25 23:59:59.500
2014-08-26 00:00:00.000 --this is wrong!

and finally the third (correctly) matches: 最后第三个(正确)匹配:

2014-08-25 23:59:59.000
2014-08-25 23:59:59.500
select * from Info
  where DateColumn >='2014-08-25 00:00:00' 
    and datecolumn<='2014-08-25 23:59:59'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM