Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting records in mysql db from 1, 7, and 30 days ago with datetime and php

Im using the following query to target results that are exactly X days older than current time.

SELECT  *,
        DATE_FORMAT(datetime, '%m/%d/%Y') 
   FROM table 
  WHERE datetime BETWEEN SYSDATE() - INTERVAL 30 DAY 
                     AND SYSDATE() 
ORDER BY ID DESC

Problem is its returning data from current day if a record from exactly 30 days ago doesnt exist, as well as irrelevant data

is there a better way of doing this?

like image 238
mrpatg Avatar asked Jul 19 '10 17:07

mrpatg


People also ask

How can I get specific date records in MySQL?

You can use DATE() from MySQL to select records with a particular date. The syntax is as follows. SELECT *from yourTableName WHERE DATE(yourDateColumnName)='anyDate'; To understand the above syntax, let us first create a table.

How do I get last 7 days data in SQL query?

We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 7 days in the past.

How do I query between two dates using MySQL?

select *from yourTableName where yourColumnName between 'yourStartingDate' and curdate().

How do I get last 30 days records in SQL?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).


1 Answers

BETWEEN includes all values in between the two arguments, including the value at each end. In other words, BETWEEN 1 AND 4 includes values 1, 2, 3, and 4. Not just 1 and 4, and not just 2 and 3.

If you just want dates from the single day that is 30 days ago, try this:

SELECT  *,
        DATE_FORMAT(datetime, '%m/%d/%Y') 
   FROM table 
  WHERE DATE(datetime) = CURDATE() - INTERVAL 30 DAY 
ORDER BY ID DESC

Use CURDATE() instead of SYSDATE() because CURDATE() returns a date without a time component.

like image 131
Bill Karwin Avatar answered Sep 27 '22 21:09

Bill Karwin