MySQL queries data from yesterday, today, 7 days, last 30 days, this month, and last month, and mysql
During development or statistics, we may need to count the data of a table. For example, view new articles today and calculate the number of new users this month. There are many similar requirements and it is very common. You can use SQL skills to complete these tasks. I have summarized some of the SQL statements used and hope to help you. I also welcome comments or comments.
#===================================================== ========## SELECT * FROM table name yesterday WHERE TO_DAYS (NOW ()) -TO_DAYS (time field name) <= 1 # SELECT * FROM table name today WHERE TO_DAYS (time field name) = TO_DAYS (NOW ());
#7-day select * FROM table name where DATE_SUB (CURDATE (), INTERVAL 7 DAY) <= DATE (time field name) # SELECT * FROM table name in the last 30 days where DATE_SUB (CURDATE (), INTERVAL 30 DAY) <= DATE (time field name) # SELECT * FROM table name in this month WHERE DATE_FORMAT (time field name, '% Y % m') = DATE_FORMAT (CURDATE (),' % Y % m ')
# SELECT * FROM table name in the previous month WHERE PERIOD_DIFF (DATE_FORMAT (NOW (), '% Y % m'), DATE_FORMAT (time field name,' % Y % m ')) = 1 #=================================================== ============================## query data for the current quarter select * FROM table name where quarter (time field name) = QUARTER (NOW (); # SELECT * FROM table name where quarter (time field name) = QUARTER (DATE_SUB (NOW (), INTERVAL 1 QUARTER )); # query current YEAR data SELECT * FROM table name where year (time field name) = YEAR (NOW (); # query previous YEAR data SELECT * FROM table name where year (time field name) = YEAR (DATE_SUB (NOW (), INTERVAL 1 YEAR )); #===================================================== ======================## query data for the current week SELECT * FROM table name where yearweek (DATE_SUB (time field name, '% Y-% m-% D') = YEARWEEK (NOW ());
# SELECT * FROM table name where yearweek (DATE_SUB (time field name, '% Y-% m-% D') = YEARWEEK (NOW ()-1;
# SELECT * FROM table name WHERE DATE_SUB (time field name, '% Y-% m') = DATE_SUB (NOW (),' % Y-% m ')
# SELECT * FROM table name WHERE time field name BETWEEN DATE_SUB (NOW (), INTERVAL 6 MONTH) ANDNOW ();
# SELECT * FROM table name WHERE DATE_SUB (time field name, '% Y-% m') = DATE_SUB (CURDATE (), INTERVAL 1 MONTH ), '% Y-% m') the article is published on the langdu cloud website, portal: http://www.wolfbe.com/detail/201608/291.html