Mysql queries for date difference in days - php

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.

Related

Get Records 30 minutes before date and time

Been trying to get this to work for 2 days and this is frustrating me.
Trying to get records 30 minutes before a date/time (Format in database is datetime).
This is what I have:
select id
from tbl_events
WHERE DATE_SUB(NOW(), INTERVAL -30 MINUTE) = DATE_FORMAT(start, '%Y-%m-%d %H:%i:%s')
What the heck am I missing?
Thanks
You already use the function DATE_SUB() so within that function you can simply use INTERVAL 30 MINUTE without the minus sign.
You also don't have to format start if it is a datetime or timestamp field.
Finally you shouldn't use = because times are hardly every exactly equal.
This gives this query:
select id
from tbl_events
WHERE start < DATE_SUB(NOW(), INTERVAL 30 MINUTE)
Probably. It's not extremely clear what you're trying to do.

Request to find out the date in 2 days

How to write a sql query to find out that there are 2 days left before the current date.
In php, this can be done via:
$res['end_date'] - time () < 86400 * 3;
How can I do the same after 1 sql query, well or better, only 2 days, if less so that it does not work out, well, if it works out, it's okay.
UPD:
It is necessary to compose a sql query that will select only those records that have 2 days left before the end_date expires
The type is int for the field end_date and is stored via the time () function in php.
Can't compose a WHERE clause.
You can use the FROM_UNIXTIME function to convert it to a DateTime you can then use the NOW() plus 2 days to check if the date is under 2 days. You then have to check that the date is before the current time otherwise you'll get dates that have already gone.
SELECT
end_date
FROM
table
WHERE
FROM_UNIXTIME(end_date) <= NOW() + INTERVAL 2 DAY
AND
FROM_UNIXTIME(end_date) > NOW()
Assuming that you are storing an epoch timestamp (the number of seconds since January 1st, 1970), I would recommend:
select *
from mytable
where end_date >= unix_timestamp() and end_date < unix_timestamp() + 2 * 24 * 60 * 60
unix_timestamp() gives you the current epoch. You can use simple math to add two days to that.
The upside of this approach is that this does direct filtering against the store value, so this can take advantagae of an index on end_date - as opposed to converting the timestamp to a date, which requires converting the whole column before the filtering can happen. So this is much more efficient.
You can ajust the inequalities as you prefer. I used a half-open interval (inclusive on the lower bound and exclusive on the upper bound), which is a widely used approach.
I ended up doing this:
$time = time();
$params = $db->query("SELECT * FROM `params` WHERE (`end_date` - {$time}) < 86400 * 3");
And it worked.
I always do
select *
from mytable
where FROM_UNIXTIME(end_date) < NOW() + INTERVAL 2 DAY
This will get results where two days in the future is ahead of the end date ie, anything that will end within 2 days (or has already ended as I didn't add a check for that)
Edit: I see you can't use where
If you cannot use where clause
select FROM_UNIXTIME(end_date) - INTERVAL 2 DAY as end_date
from mytable
And then check in php if the result is before or after. This will show all results however

How to make a date interval in a MySQL query?

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.

SQL DATE and TIME to DATETIME

I have date and time column in my table. I want to select all objects which has date and time larger than current time plus one hour:
I have tried the following:
SELECT * FROM mytable WHERE date >= CURDATE() AND time >= TIME(NOW()+INTERVAL 1 hour)
However this is logically not correct. If date is tomorrow and time is less than current HH:MM it will not select that record.
How can I use my date and time to compare with current datetime?
I am using php 5.2 with mysql
First of all, I recommend using a DATETIME column to make this filtering more efficent. However, this works if you cannot change:
SELECT * FROM mytable
WHERE (date = CURDATE() AND time >= TIME(NOW() + INTERVAL 1 hour))
OR date > CURDATE()
You can split your condition into two conditions...
When the date is equal to today and more than an hour ahead of the current time:
date == CURDATE() AND time >= TIME(NOW()+INTERVAL 1 hour)
When the date is greater than today:
date > CURDATE()
...and chain them together using OR and parentheses:
SELECT * FROM mytable WHERE (date == CURDATE() AND time >= TIME(NOW()+INTERVAL 1 hour)) OR date > CURDATE()
First check whether the date is today and if time is greater then current time. The second condition is to check whether the date is greater than current date. Because if the date is greater then current date then automatically it's time is ahead.
SELECT * FROM mytable
WHERE (date = CURDATE() AND time >= TIME(NOW() + INTERVAL 1 hour))
OR date > CURDATE()
SELECT * FROM mytable WHERE date >= CURDATE() AND time >= TIME(HOUR(NOW()) + 1);
or maybe just
SELECT * FROM mytable WHERE date >= CURDATE() AND time >= HOUR(NOW()) + 1;
As indicated by #Pekka, all the answers posted so far will give the wrong answer between 11pm and midnight. I don't work with MySQL, but I can look stuff up. A better approach seems to be the timestamp() function.
This reference states:
With two arguments, it adds the time expression expr2 to the date
or datetime expression expr1 and returns the result as a datetime value.
Why not use timestamp() with two arguments?
You can do this.
SELECT
*
FROM
mytable
WHERE
CONCAT( date, " ", time ) > (NOW() + INTERVAL 1 HOUR );
Personally I suggest that you get rid of the separate fields for date and time and create a consolidated 'DATETIME' field. I also suggest adding an INDEX to that field.
That would make your queries better and faster. :)

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

Categories