How to specify a relative date in MySQL?
I already know how to, for instance, get tomorrow's date in a query in SQL; either use ADDDATE(CURDATE(),开发者_开发百科1)
or DATE_ADD(CURDATE(), INTERVAL 1 DAYS)
(or something like that).
But how would I get a date that is a bit more eccentric, for example the 10th of next month?
UPD
STR_TO_DATE(CONCAT(YEAR(NOW()) + IF(MONTH(NOW()) = 12, 1, 0), '-', IF(MONTH(NOW()) = 12, 0, MONTH(NOW())) + 1, '-', 10), '%Y-%m-%d')
yes, it looks weird, but it solves "now is december" issue ;-)
There's no such thing in MySQL, this has to be done before DB. At least with the flexibility you suggest when wanting generally "more eccentric".
Perhaps not a good idea to have that kind of logic in a query anyways? Depending on your case ofcourse.
I'm going to start by quoting a comment from above, and saying I totally agree with it:
Did you literally want to find the 10th of next month? My assumption was you wanted some basic natural language processing, which is pretty much not doable in MySQL. – Alexander Sagen 6 hours ago
However, if you're absolutly, totally, desperate, then you could look at writing your own function to do this. You'd have to work out first exactly what sort of inputs you're going to send (i.e are you literally going to pass a single string value such as "10th of next month"), or can this be represented as day,month , so 10,+1 in the example. If it's the latter, it makes things a lot easier. Otherwise, you're looking at evaluating the text of the input and making decisions about what to do. Big IF statements, basically. It's doable - but it isn't what SQL was made for.
For complex date logic you might want to consider pre-generating a date table and selecting from it. Having the appropriate columns will make selection with where clauses easier. Its a common and almost required technique for data warehouses. Something like this perhaps:
http://www.ipcdesigns.com/dim_date/
Then you can do (if I understood his schema correctly):
SELECT
full_date
FROM date_table
WHERE date_table.day_num_of_month = 10 AND
date_table.month_num_overall = (SELECT month_num_overall+1 FROM date_table WHERE full_date = NOW())
精彩评论