Comparing dates and times in different fields - php

Now, I've a problem with the following query:
SELECT *
FROM table
WHERE date > CURDATE()
OR date = CURDATE()
AND time > CURTIME()
It's return rows with date > of today but I need also rows with date of today but with time > of the current time.

You need to put the related clauses inside parenthesis:
SELECT *
FROM table
WHERE date > CURDATE()
OR (
date = CURDATE()
AND time > CURTIME()
)

You should use the appropriate date/time functions instead of complicating yourself with complex WHERE clauses:
SELECT * FROM TABLE
WHERE ADDTIME(date, time) > NOW()
More information on the ADDTIME function in this link.

Related

MySQL date comparisons returning different results

I have a query selecting rows between dates.
SELECT * FROM `table` WHERE statusDate >= '2014-10-01' AND statusDate <= '2014-10-31'
When I use the above query it returns significantly less rows than the following query...
SELECT * FROM `table` WHERE statusDate > '2014-09-30' AND statusDate < '2014-11-01'
Technically I'd have thought it would return the same results but it's not.
My understanding on the bottom query is that it selects from dates above and below the dates stated, not including. Why would the results be different?
If statusDate is a DATETIME column, the time of day will cause the results to be different for rows on the last day of the month. When you convert the date 2014-10-31 to a DATETIME, it's 2014-10-31 00:00:00. If there's a row whose statusDate is 2014-10-31 09:23:11, it will not be selected by the first query, but it will be selected by the second query.
You can solve this by using:
WHERE statusDate >= '2014-10-01' AND DATE(statusDate) <= '2014-10-31'
or you can add the time to the WHER clause:
WHERE statusDate >= '2014-10-01' AND statusDate <= '2014-10-31 23:59:59'

Mysql Query back to midnight only

I have this query that looks up results from a database for the last twenty minutes, now i know how to look up in hours, days, etc, but is it possible to look up only as far back as midnight of that day. so when ever the query is run and what ever time it only looks back as far as midnight?
SELECT * FROM ip_stats WHERE date >= ( NOW() - INTERVAL 20 MINUTE ) and ip='$ip'
This is my code but is there away in which i can replace the interval for a specific time.
Any help would be appreciated.
Looking back to midnight of the current day is the same as looking at the current date with no time component. You can therefore use DATE() to truncate the datetime column date to only the date portion, and compare it to CURDATE().
SELECT * FROM ip_stats WHERE DATE(date) = CURDATE() and ip='$ip'
SELECT * FROM ip_stats WHERE date >= ( NOW() - INTERVAL 20 MINUTE ) AND date >= CURDATE() and ip='$ip'
Just make the column date be bigger than the curdate (which is the starting of this day).
SELECT * FROM ip_stats
WHERE date >= ( NOW() - INTERVAL 20 MINUTE )
and date > CURDATE()
and ip='$ip'
You can use CURDATE() to get rows since midnight of the current day:
SELECT * FROM ip_stats WHERE date >= CURDATE() and ip='$ip'
SELECT *
FROM ip_stats
WHERE date >= GREATEST( NOW() - INTERVAL 20 MINUTE, CURRENT_DATE )
AND ip = '$ip'

SQL and date comparison

I have a sql statement, i select a few items, but I need to make sure that the date i have saved is greater then the current date.
SELECT * FROM table WHERE column_date > current_date
How do I make the code over, working?
Column date is saved like this 0000-00-00 00:00:00 (usual save, in other words).
This is what I try to achieve: AND time > current_date OR time == NULL But it ain't working. The time column is currently 0000-00-00 00:00:00 which is NULL, right?
Or how can I do, it must be greater than or equal to 0000-00-00 00:00:00
If you are using MySQL, NOW() should do the trick.
SELECT * FROM table WHERE column_date > NOW()
If you want to eliminate the time value and just compare to date value, following could be used:
SELECT * FROM table WHERE column_date > CURDATE()
You could use the Mysql Function NOW():
SELECT * FROM table WHERE column_date > NOW()
As per this documentation article, 0000-00-00 is a "dummy date" that can be used instead of NULL, which means 0000-00-00 itself is not NULL.
Given that 0000-00-00 cannot be greater than any other date, you should use either a condition with OR:
SELECT * FROM table WHERE column_date > NOW() OR column_date = '0000-00-00'
or a union:
SELECT * FROM table WHERE column_date > NOW()
UNION ALL
SELECT * FROM table WHERE column_date = '0000-00-00'
Alternatively you could use a construct like this:
SELECT *
FROM table
WHERE IFNULL(NULLIF(column_name, '0000-00-00'), '9999-12-31') > NOW()
But that would probably prohibit the query from taking advantage of the index on column_date, if any.

How do I get rows for last 24 hours by unixstamp

I have this;
$long = "86400";
$query = "SELECT * FROM users WHERE unixdate = UNIX_TIMESTAMP()-$long
ORDER BY unixdate DESC";
But it doesn't work. I would like to show all new users within 24 hours
You can do that query completely in MySQL with
SELECT col1, col2, otherCols
FROM yourTable
WHERE timestamp_col > (NOW() - INTERVAL 24 HOUR)
The expression (NOW() - INTERVAL 24 HOUR) returns the date 24 hours ago. MySql is smart enough to handle comparisons between Time related column types.
If timestamp_col is not a time related type, but something like a varchar or int column you have to use FROM_UNIXTIME on the column or adjust the above query to read
SELECT col1, col2, otherCols
FROM yourTable
WHERE timestamp_col > UNIX_TIMESTAMP( NOW() - INTERVAL 24 HOUR )
See DATE_SUB and DATE_ADD in the MySql Manual.
Use > instead of =. At the moment, you are querying for entries created at a certain second which will hardly ever match.
You're looking for new users within the last 24h, not exactly 24h. So you have to use the > (greater than) operator instead of = (equals).
$long = "86400";
$query = "SELECT * FROM users WHERE unixdate > UNIX_TIMESTAMP()-$long ORDER BY unixdate DESC";
By the way, PHP has a function equivalent to MySQL UNIX_TIMESTAMP() function: time();
You must convert the timestamp file to date for the comparison.
SELECT * FROM table WHERE (from_unixtime(unixdate) >= NOW() - INTERVAL 1 DAY)

how do I get month from date in mysql

I want to be able to fetch results from mysql with a statement like this:
SELECT *
FROM table
WHERE amount > 1000
But I want to fetch the result constrained to a certain a month and year (based on input from user)... I was trying like this:
SELECT *
FROM table
WHERE amount > 1000
AND dateStart = MONTH('$m')
...$m being a month but it gave error.
In that table, it actually have two dates: startDate and endDate but I am focusing on startDate. The input values would be month and year. How do I phrase the SQL statement that gets the results based on that month of that year?
You were close - got the comparison backwards (assuming startDate is a DATETIME or TIMESTAMP data type):
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(dateStart) = {$m}
Caveats:
Mind that you are using mysql_escape_string or you risk SQL injection attacks.
Function calls on columns means that an index, if one exists, can not be used
Alternatives:
Because using functions on columns can't use indexes, a better approach would be to use BETWEEN and the STR_TO_DATE functions:
WHERE startdate BETWEEN STR_TO_DATE([start_date], [format])
AND STR_TO_DATE([end_date], [format])
See the documentation for formatting syntax.
Reference:
MONTH
YEAR
BETWEEN
STR_TO_DATE
Use the month() function.
select month(now());
Try this:
SELECT *
FROM table
WHERE amount > 1000 AND MONTH(dateStart) = MONTH('$m') AND YEAR(dateStart) = YEAR('$m')
E.g.
$date = sprintf("'%04d-%02d-01'", $year, $month);
$query = "
SELECT
x,y,dateStart
FROM
tablename
WHERE
AND amount > 1000
AND dateStart >= $date
AND dateStart < $date+Interval 1 month
";
mysql_query($query, ...
This will create a query like e.g.
WHERE
AND amount > 1000
AND dateStart >= '2010-01-01'
AND dateStart < '2010-01-01'+Interval 1 month
+ Interval 1 month is an alternative to date_add().
SELECT Date('2010-01-01'+Interval 1 month)-> 2010-02-01
SELECT Date('2010-12-01'+Interval 1 month)-> 2011-01-01
This way you always get the first day of the following month. The records you want must have a dateStart before that date but after/equal to the first day of the month (and year) you've passed to sprintf().
'2010-01-01'+Interval 1 month doesn't change between rows. MySQL will calculate the term only once and can utilize indices for the search.
Try this
SELECT *
FROM table
WHERE amount > 1000
AND MONTH(datestart)
GROUP BY EXTRACT(YEAR_MONTH FROM datestart)
Try this if(date field is text then convert this string to date):
SELECT * FROM `table_name` WHERE MONTH(STR_TO_DATE(date,'%d/%m/%Y'))='11'
//This will give month number MONTH(STR_TO_DATE(date,'%d/%m/%Y'))
//If its return 11 then its November
// Change date format with your date string format %d/%m/%Y
Works in: MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23
Day:
SELECT EXTRACT(DAY FROM "2017-06-15");
Month:
SELECT EXTRACT(MONTH FROM "2017-06-15");
Year:
SELECT EXTRACT(YEAR FROM "2017-06-15");

Categories