MySQL query today, yesterday, nearly 7 days, nearly 30 days, this month, last month data

Source: Internet
Author: User

Recent projects have used the ability to query data records in the current month, the initial idea is to construct a time period in the logical business query, when writing SQL statements feel very troublesome. So I went to search the Internet to see if there was a simple way to do it. Sure enough, network resources are strong. The following combination of my project table to the MySQL query today, yesterday, nearly 7 days, nearly 30 days, this month, the last month of data SQL statements recorded.

There is a ad_protrack_t table that tracks product Time fields Crt_time

Query today's information records:

SELECT * from ad_protrack_t  where To_days (' crt_time ') = To_days (now ());
Query yesterday's information record:
SELECT * from ad_protrack_t where To_days (now ()) –to_days (' Crt_time ') <= 1;
Check the information record for nearly 7 days:
SELECT * from ad_protrack_t where Date_sub (Curdate (), INTERVAL 7 day) <= date (' Crt_time ');
Check the information record for nearly 30 days:
SELECT * from ad_protrack_t  where Date_sub (Curdate (), INTERVAL) <= date (' Crt_time ');
Query this month's information records:
SELECT * from ad_protrack_t  where Date_format (' crt_time ', '%y%m ') = Date_format (Curdate (), '%y%m ');
Query the information record for the previous January:

SELECT * from ad_protrack_t where Period_diff (Date_format (now (), '%y%m '), Date_format (' crt_time ', '%y%m ')) = 1;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.