mysql - How to get data by date range given only month and year

前端 未结 5 663
轮回少年
轮回少年 2021-01-15 16:18

Below is my mysql table:

--------------------------
ID  Date_From   Date_To
--------------------------
1   2011-02-01  2011-02-28
2   2012-09-01  2012-09-30
         


        
相关标签:
5条回答
  • 2021-01-15 16:51

    In id 6 the from date is 2013-01-01 and it fails in 2013-01-01 as the month is 01 which is less than 10. As you have mentioned all and condition so any false will not include that record.

    0 讨论(0)
  • 2021-01-15 16:53

    You need to use query like this:

    SELECT * FROM TIME_PERIOD WHERE 
    (YEAR(DATE_FROM) >= '2013' OR (YEAR(DATE_FROM) >= '2012' AND
     MONTH(DATE_FROM) >= '10')) AND 
    (YEAR(DATE_TO) <= '2013' AND MONTH(DATE_TO) <= '12');
    
    0 讨论(0)
  • 2021-01-15 16:55

    Month seems to be 01 in record 6. It wont return that because MONTH(DATE_FROM) >= '10'

    0 讨论(0)
  • 2021-01-15 16:57

    You can use this command to get your result ...

    SELECT * FROM `TIME_PERIOD` WHERE `DATE_FROM` >= '2012-10-01' AND `DATE_TO` <= '2013-01-30'
    
    0 讨论(0)
  • 2021-01-15 16:58

    You can create a separate column as year_month like YYYYMM and create two triggers to automatically update the column ON INSERT and ON UPDATE if required.

    Then the query would be as simple as

    WHERE year_month >= 201210 and year_month <= 201312

    0 讨论(0)
提交回复
热议问题