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. :)
Related
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
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.
I want to return records from database 15 days old from end _date to till end_date!
I am searching for the query for last 3 days!
However. I want your help to do a query. Its simple but I'm not sure how to do it.
I wrote query something like :
SELECT *
FROM bid_post
WHERE ending_date
BETWEEN DATE_SUB( DATE(`ending_date`) , INTERVAL 15
DAY )
AND ending_date >= CURDATE()
But it is not working !
The data column is a Varchar type. I am storing date as YYYY-mm-dd format
Does somebody now how can I accomplish this?
Thanks.
Please try with this query
SELECT *
FROM bid_post
WHERE ending_date between DATE_SUB( CURDATE() , INTERVAL 15 DAY )
AND CURDATE()
You should never store dates as varchar since these are not real dates and you need to store them using mysql native date data types.
Since the format is Y-m-d you may not need to do a conversion using str_to_date function and can use the query as
select * from bid_post
where
ending_date between date_sub(curdate(),interval 5 day) and curdate()
This will give you data from last 15 days till today.
Using conversion to real date you need str_to_date as
select * from bid_post
where
str_to_date(ending_date,'%Y-%m-%d') between date_sub(curdate(),interval 5 day) and curdate() ;
DEMO
Here is my table
I am executing a query that give me result of fields whose item_valid_from must be greater than today's date and item_valid_to must be less than today.
My query is
select *
from tbl1
where item_valid_from >= CurDate()
and item_valid_to < CurDate()
Any Solution?
I would advise you to change item_valid_* field formats to DATE field format. You will save you a lot of trouble in the future.
But ok, if you don't want to do that, then you can use STR_TO_DATE() function:
SELECT *
FROM `table`
WHERE CURDATE() BETWEEN STR_TO_DATE(`from_field`, '%d-%m-%Y') AND STR_TO_DATE(`to_field`, '%d-%m-%Y')
demo
Assuming the datatype item_valid_from and item_valid_to is DATE, TIMESTAMP, etc, then you have your operators backwards. Think of the time as seconds since 1970, since this is how it is stored in unix time. That means that item_valid_from is going to be smaller than item_valid_to, and you want it to display when today is somewhere between them. You want the item_valid_from to be less than or equal to now, and the item_valid_to to be greater than now (not in the past).
SELECT *
FROM tbl1
WHERE item_valid_from <= CURDATE() AND item_valid_to > CURDATE()
See this SQL Fiddle for an example, only 2-4 are valid and show up in the results being valid from a date in the past and expiring on a date in the future.
You have to use following query which change current date format then compare date and fetch result :
SELECT *
FROM tbl1
WHERE date_format(item_valid_from,'%d-%m-%Y') >= date_format(CurDate( ),'%d-%m-%Y')
AND date_format(item_valid_to,'%d-%m-%Y') < date_format(CurDate( ),'%d-%m-%Y')
Please Check this :http://sqlfiddle.com/#!2/561d0/2
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