Creating Date Objects from Disparate Date Fields in MySQL
Your predicament, where a database schema's date representation is split into individual day, month, and year fields, presents a unique challenge for date manipulation in SQL. However, using the following approach, you can effectively construct date objects from these separate fields.
To create a DATETIME object from integer values representing year, month, and day, utilize the combination of MAKEDATE() and DATE_ADD() functions.
By combining these functions, you can construct dates gradually:
Example:
SELECT DATE_ADD(DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH), INTERVAL (11)-1 DAY);
This query returns the DATETIME object for March 11, 2013.
Now, you can employ this technique to construct date ranges for comparison in your SQL queries:
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';
This query retrieves all records from the date table with dates falling between January 1, 2013, and January 1, 2014.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3