mysql date processing commonly used in several sql

- Today
SELECT DATE_FORMAT (NOW (), ' % Y-% m-% d 00:00:00') AS ' from today';
the SELECT the DATE_FORMAT (the NOW (), 'M-% D%% Y-23 is: 59:59 ') AS' end of today ';

- yesterday
SELECT DATE_FORMAT (DATE_SUB (CURDATE () , INTERVAL 1 dAY),'% Y-% m-% d 00:00:00 ') AS' Since yesterday ';
SELECT DATE_FORMAT (DATE_SUB (CURDATE () , INTERVAL 1 DAY), '% Y-% m-% d 23:59:59') AS ' end of the last';

- week
SELECT DATE_FORMAT (DATE_SUB (DATE_SUB (CURDATE () , INTERVAL WEEKDAY (CURDATE ()) DAY), INTERVAL 1 WEEK), '% Y-% m-% d 00:00:00') AS ' Monday';
the SELECT the DATE_FORMAT (SUBDATE (CURDATE (), WEEKDAY ( CURDATE ()) + 1), '% Y-% m-% d 23:59:59') AS ' weekend';

- week
SELECT DATE_FORMAT (SUBDATE (CURDATE () , DATE_FORMAT (CURDATE (), ' % w ') - 1), '% Y-% m-% d 00:00:00 ') The AS 'Monday';
SELECT DATE_FORMAT (SUBDATE (CURDATE () , DATE_FORMAT (CURDATE (), '% w') - 7), '% Y-% m-% d 23:59:59') AS ' weekend';
- above This week algorithm be a problem, because mysql is in accordance with Sunday the first day of a week, if the current is Sunday, it will scheduled for the following week.
the SELECT the DATE_FORMAT (DATE_SUB (CURDATE (), INTERVAL WEEKDAY (CURDATE () ) DAY), '% Y-% m-% d 00:00:00') AS ' Monday';
the SELECT the DATE_FORMAT (DATE_ADD (SUBDATE (CURDATE (), WEEKDAY (CURDATE ())), the INTERVAL DAY. 6) , '% Y-% m-% d 23:59:59') AS ' weekend';

- month
SELECT DATE_FORMAT (DATE_SUB (CURDATE () , INTERVAL 1 mONTH), '% Y-% m-01 00 : 00: 00 ') AS' early on ';
the SELECT the DATE_FORMAT (LAST_DAY (for DATE_SUB (CURDATE (), the INTERVAL mONTH. 1)),'% Y-M-% D% 23:59:59 ') the AS' last month ' ;

- month
SELECT DATE_FORMAT (CURDATE (), ' % Y-% m-01 00:00:00') AS ' this month';
SELECT DATE_FORMAT( LAST_DAY(CURDATE()), '%Y-%m-%d 23:59:59') AS '本月末';

 

Reprinted from: http://www.cppblog.com/tx7do/archive/2017/07/19/215119.html

Guess you like

Origin www.cnblogs.com/liumyblog/p/11926486.html