简体   繁体   English

使用mysql查询检查日期是否在给定的日期范围内

[英]checking if a date falls in given date range using mysql query

I have these two columns in my database table 'mycodes' 我的数据库表“ mycodes”中有这两列

code_valid_from_date
code_expiry_date

I need to check if a given date falls in valid period of the dates given in mycodes tables. 我需要检查给定的日期是否在mycodes表中给出的日期的有效期内。

For example, 例如,

mycodes
id, code_valid_from_date, code_expiry_date, name
1, 2013-08-01, 2013-08-28, 'Code 1'
2, 2013-08-29, 2013-09-20, 'Code 2'
3, 2013-07-01, 2013-07-28, 'Code 3'

I tried this query, 我试过这个查询

SELECT
DATEDIFF(NOW(), code_valid_from_date) valid_from_days, 
DATEDIFF(code_expiry_date, NOW()) expiry_days_left
FROM mycodes

then in my php code I check both of these DATEDIFF are positive numbers then its a valid code. 然后在我的PHP代码中,我检查这两个DATEDIFF均为正数,然后为其有效代码。 What if I have to compute this validity in the mysql query itself rather than checking using PHP? 如果我必须在mysql查询本身中计算此有效性而不是使用PHP进行检查怎么​​办? How do I do that? 我怎么做?

PS: I could also use a BETWEEN in WHERE clause but that will return rows which fall in that given range but I need to list all the records with status of expired or not expired. PS:我也可以在WHERE子句中使用BETWEEN,但是它将返回属于该给定范围的行,但是我需要列出状态为过期或未过期的所有记录。

Mysql知道可以比较日期,因此您可以使用类似以下的内容:

SELECT (NOW() >= code_valid_from_date AND NOW() <= code_expiry_date) AS valid FROM mycodes

选择(NOW()在code_valid_from_date和code_expiry_date之间)作为有效自mycodes

This is my code to find if a date range falls within another date range. 这是我的代码,用于查找某个日期范围是否在另一个日期范围内。 I'm sure you could modify my choosing the same date as your arrival and departure date. 我确定您可以将我选择的日期修改为到达和离开的日期。

Example that works for me and my queries: 适用于我和我的查询的示例:

SET @PerBeg = ’2010-01-01’;
  SET @PerEnd = ’2010-01-31’;

  SELECT  
      Reservation.ArrivalDate AS ArrivalDate, 
      Reservation.DepartureDate AS DepartureDate, 
  . . . 

  WHERE

  fBoolActyInPeriod(ArrivalDate,DepartureDate,@PerBeg,@PerEnd)

using these functions 使用这些功能

  FUNCTION fBoolActyInPeriod contains this code
  RETURN IF (fBoolFirstDateEarlier(ActyEnd, PerBeg) OR fBoolFirstDateEarlier(PerEnd, ActyBeg),0, 1)

  FUNCTION fBoolFirstDateEarlier contains this code
  RETURN IF (DATEDIFF(first, second) < 0, 1, 0)

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

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