How to make a date interval in a MySQL query? - php

I want to make a date interval in a MySQL query. The date is extracted dynamically from an HTML Form and I want to search if something is between 2 days after and after a fixed date. I've made an example but it's not working well.
SELECT * FROM `sessions` WHERE `start_date` = '2014-05-12'
or `start_date` between DATE_SUB(start_date, INTERVAL 1 DAY)
and DATE_ADD(start_date, INTERVAL 1 DAY)
Any other propositions ?

If I'm not wrong every time this query is resulting all rows from the sessions table. Let's take a look at this particular part of the query,
start_date between DATE_SUB(start_date, INTERVAL 1 DAY)
and DATE_ADD(start_date, INTERVAL 1 DAY),
So if the start_date value of a row is 22-07-2014 the query translates to,
start_date between 21-07-2014 and 23-07-2014)
So every row satisfies the condition as every date x is between x - 1th day and x + 1th day.
So if you want to execute the query to find a date between a certain interval, try
start_date between DATE_SUB('$start_date', INTERVAL 1 DAY)
and DATE_ADD('$start_date', INTERVAL 1 DAY)
instead. Note that '$start_date' is a php variable that is the date you are comparing the row with.

Related

MySQL query for checking if one date is close to current date

I have two columns(date field, time field) which are storing date and time in string and first step is to combine these two fields so i can compare them with current date(i'm not sure if i'm doing that right). Second step is writing query which should select records only if obtained date from these two columns is close to current date. And that date should be between current date and 4 hours before current date because after that something will happen with all those records if some conditions are not met.
Format of columns date and time:
event_date = 'yyyy/MM/dd'
event_time = 'HH:mm'
So here is my query:
SELECT *
FROM `events`
WHERE DATE_SUB( NOW( ) , INTERVAL 4 HOUR )
< ADDTIME( event_date, event_time )
Maybe i should firstly convert these strings to date and then work with them or something else? All in all if i have some data with these dates for example:
1. 2017-02-26 10:00
2. 2017-02-26 11:00
3. 2017-02-27 10:00
And current datetime is: 2017-02-26 06:00
. In this case i would get only 1 record and when one hour pass or 2017-02-26 07:00 then i will get 2 records
If event_date is the date of the event and event_time is the time, you could combine them using the timestamp mysql function:
select event_date, event_time, timestamp(event_date, event_time)
from events;
but it's usually a good idea to actually store the date and time information in a single field e.g. event_datetime
you can then write your query like this:
select *
from
events
where
event_datetime between now() and now() + interval 4 hour;
this will return all events starting from now and 4 hours in the future. Or if you want the events from the last 4 hour in the past try with:
event_datetime between now() - interval 4 hour and now();
You should convert your date and time to a proper datetime data type. That said, you can do something like the following to accomplish what you want:
SELECT * FROM `events`
WHERE STR_TO_DATE(CONCAT(event_date,' ',event_time), '%Y/%m/%d %H:%i')
BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 4 HOUR)
The query will return all rows between now and 4 hours from now.
UPDATE: I just noticed the answer from #fthiella, using timestamp probably gives better performance than the example I provided.

Mysql queries for date difference in days

Need help here, having an mysql table called APPROVAL, there having an id,dateandtime and level, i need a query that selects the id alone with the following condition.
Taking date alone from database and comparing it with current system date, if the days exceeds above 30 and below 60 and also level = 5.
How can I write a query for this.
Thanks in advance.
MySQL has good date arithmetic. For example, the expression
CURDATE() + INTERVAL 30 DAY
gives a datetime value denoting midnight 30 days hence. Similarly
CURDATE() + INTERVAL 61 DAY
yields midnight on the 61st day.
So a query of the form
SELECT ID
FROM APPROVAL
WHERE Level = 5
AND `DateTime` >= CURDATE() + INTERVAL 30 DAY
AND `DateTime` < CURDATE() + INTERVAL 61 DAY
will yield what you want. Notice the use of >= for the beginning of the range of days, and the use of < and an extra day for the end of the range. We do that because we want all items from the 60th day, and none from the 61st day.
A compound index on (Level, DateTime) will make this query very efficient to satisfy.
Notice that an expression like
DATE(`DateTime`) <= CURDATE() + INTERVAL 60 DAY /* slow! */
will also yield correct results, but the presence of the the DATE() function call on the column to be searched makes it unsargeable. That is, it makes MySQL unable to use an index to satisfy the search.
Ok so use this query to retrieve all the IDs that match level 5 and date diff between 30 and 60 compared to the current date.
SELECT id
FROM APPROVAL
WHERE level = 5 && DATEDIFF(NOW(), dateandtime) BETWEEN 30 AND 60
I'd suggest you to order them dy date DESC too.
Hope that helps
I hope, I understood your problem correctly.
select `ID`
from APPROVAL
where `Level` = 5
and ( DATE(`DateTime`) > curdate() + interval 30 day
and DATE(`DateTime`) < curdate() + interval 60 day )
order by `ID` asc;
Where DATE() gets the date from a datetime and CURDATE() is the current system date. With interval you can manipulate a date expression whitout having to worry about its limits.

Need all MySQL rows with dates in the next 7 days, but the date column is not formatted normally

I have a column in my database 'scheduledDate', I need all rows in the database that have a scheduledDate within 7 days from today.
I could use a query like this:
SELECT * FROM tblName WHERE `scheduledDate` > DATE_ADD(now(), INTERVAL 7 DAY
The only problem is, the 'scheduledDate' column is not formatted as a mysql timestamp (YYYY-MM-DD HH:MM:SS), but is formatted just as a standard American Date (07/09/2014). Is there a way to grab all rows within the next 7 days in my query? I was thinking that it might be possible using DATE_FORMAT, but I have been unable to figure it out.
You can convert the string to a date using str_to_date():
WHERE str_to_date(`scheduledDate`, '%m/%d/%Y') BETWEEN now() and DATE_ADD(now(), INTERVAL 7 DAY)
The logic also needs to change. The above uses between, but this may not be the logic your really need because of the extraneous time component on now(). Perhaps this is closer:
WHERE str_to_date(`scheduledDate`, '%m/%d/%Y') BETWEEN CURRENT_DATE() and DATE_ADD(CURRENT_DATE, INTERVAL 7 DAY)
WHERE scheduledDate >= Date_Add(now(), INTERVAL -7 DAY)

Fetch rows only from specific date in mySQL

I am trying to fetch rows only from specific date (like today, yesterday or 2 days ago) in mySQL. I have a column named "date" in my rows. (which includes dates like 1365053426).
$result=mysql_query("SELECT count(*) as total from track WHERE `date` >= CURRENT_DATE
AND `date` < CURRENT_DATE + INTERVAL 1 DAY");
I have tried this query, but it returns "0". What is the correct way to do that ?
how about using BETWEEN?
SELECT COUNT(*) as TotalCount
FROM Track
WHERE Date BETWEEN CURDATE() + INTERVAL -2 DAY AND CURDATE()
How about using datediff() function?
SELECT count(*) as total from track WHERE datediff(now(),date)=interval day
note: interval day could be declare from 0 -> up depends on what previous date you want to show

Filter an html table bound to a MySQL table by date

I have an html table that displays maintenance records. There are 3 columns that have dates in the future.
I want to have a button above the table that checks whether any of these 3 dates are within the next 30 days. If so, the row is displayed and other rows that are not of immediate concern are not displayed.
What is the best approach for achieving a filter like this?
Update: I'm trying to do it in a MySQL query.
I have 3 attributes in the SQL table that are date.
Does anyone know how to query whether the dates are within the next 30 days?
Does anyone know how to query whether the dates are within the next 30 days?
Use this :
WHERE yourdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 30 DAY)
uses between, curdate() and date_add()
Update
to check multiple dates you need to do :
WHERE yourdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 30 DAY)
AND yournextdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 30 DAY)
AND anotherdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(),INTERVAL 30 DAY)

Categories