简体   繁体   中英

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. It looks like you want this query, for example if $i were 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.
  • Use + INTERVAL 1 MONTH to get the end date. 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 .
  • Instead of <=... 23:59 use < and the day after the last day you want to consider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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