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

Source: Internet
Author: User
Tags mysql query

Recent projects have used the function of querying the data record of the month, the initial idea is to construct a good time period in the logic 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 very powerful. The following combination of my project table to put MySQL query today, yesterday, nearly 7 days, nearly 30 days, this month, the last month data of SQL statements recorded.

There is a ad_protrack_t table. Tracking Product Time field Crt_time

Query today's information records:

SELECT * from ad_protrack_t  where to_days (crt_time) = To_days (now ());//This SQL is called in today's test, and it is not the desired result.

After trying to find that the ' Time field ' in parentheses of the To_days function cannot add an argument, the conversion of the add-in is null

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-day) <= 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;

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

Related Article

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.