Create date from day, month, year fields in MySQL

后端 未结 6 1012
予麋鹿
予麋鹿 2020-12-05 22:25

I am currently developing an application that displays documents and allows the members to search for these documents by a number of different parameters, one of them being

6条回答
  •  没有蜡笔的小新
    2020-12-05 23:09

    When you have integer values for year, month and day you can make a DATETIME by combining MAKEDATE() and DATE_ADD(). MAKEDATE() with a constant day of 1 will give you a DATETIME for the first day of the given year, and then you can add to it the month and day with DATE_ADD():

    mysql> SELECT MAKEDATE(2013, 1);
    +-------------------+
    | MAKEDATE(2013, 1) |
    +-------------------+
    | 2013-01-01        |
    +-------------------+
    
    mysql> SELECT DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH);
    +---------------------------------------------------+
    | DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH) |
    +---------------------------------------------------+
    | 2013-03-01                                        |
    +---------------------------------------------------+
    
    mysql> SELECT DATE_ADD(DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH), INTERVAL (11)-1 DAY);
    | DATE_ADD(DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH), INTERVAL (11)-1 DAY) |
    +----------------------------------------------------------------------------------+
    | 2013-03-11                                                                       |
    +----------------------------------------------------------------------------------+
    

    So to answer the OP's question:

    SELECT * FROM `date`
    WHERE DATE_ADD(DATE_ADD(MAKEDATE(year, 1), INTERVAL (month)-1 MONTH), INTERVAL (day)-1 DAY)
    BETWEEN '2013-01-01' AND '2014-01-01';
    

提交回复
热议问题