简体   繁体   English

SQL 两个日期范围,范围内有特定的“DAY”

[英]SQL two date range with specific “DAY” in range

This is my QUERY这是我的查询

SELECT * 
FROM tableNAME
WHERE 
st.column_date BETWEEN '" . $_SESSION['selectYear'] . "-" . str_pad($i, 2, "0", STR_PAD_LEFT) . "-11 00:00:00' AND '" . $_SESSION['selectYear'] . "-" . str_pad(($i + 1), 2, "0", STR_PAD_LEFT) . "-10 23:59:59' 

This query will bring up the issue when it come to the month 'DECEMBER'.此查询将在“十二月”月份出现问题。 Looking for help.寻求帮助。

It looks like $i is a month number.看起来$i是一个月数。 It looks like you want this query, for example if $i were 7.看起来你想要这个查询,例如如果$i是 7。

SELECT * 
  FROM tableNAME
 WHERE st.column_date BETWEEN '2019-07-11 00:00:00' 
                          AND '2019-08-10 23:59:59';

Your way of specifying this date range fails over the end of a year, as you have discovered.正如您所发现的,您指定此日期范围的方式在一年结束时会失败。

What will work for you is this query对你有用的是这个查询

SELECT * 
  FROM tableNAME
 WHERE st.column_date >= '2019-07-11' 
   AND st.column_date <  '2019-07-11' + INTERVAL 1 MONTH;
  • Give the same date parameter twice.两次给出相同的日期参数。
  • You don't need to specify the time when it's 00:00.您无需指定 00:00 的时间。
  • Use + INTERVAL 1 MONTH to get the end date.使用+ INTERVAL 1 MONTH获取结束日期。 That works correctly over ends of years.多年来,这都能正常工作。 It also happens to work correctly for months like February, even in leap years, and even if your start date is something like 2020-01-30 .即使在闰年,即使您的开始日期类似于2020-01-30 ,它也恰好在 2 月这样的月份正常工作。
  • Instead of <=... 23:59 use < and the day after the last day you want to consider.而不是<=... 23:59使用<和您要考虑的最后一天的第二天。

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

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