Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36591

Problem with mysql date query

mysql> desc persondb;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| name   | varchar(25) | YES  |     | NULL    |       |
| lname  | varchar(25) | YES  |     | NULL    |       |
| mydate | datetime    | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> select * from persondb;
+------------+--------+---------------------+
| name       | lname  | mydate              |
+------------+--------+---------------------+
| vishwanath | dalvi  | 2011-08-21 14:50:37 |
| ishwar     | dalvi  | 2011-08-21 14:50:58 |
| ganesh     | kamble | 2011-08-31 14:50:37 |
+------------+--------+---------------------+
3 rows in set (0.00 sec)

mysql> select name,mydate from persondb
    -> where date_sub(now(),INTERVAL 5 DAY)<=mydate;
+------------+---------------------+
| name       | mydate              |
+------------+---------------------+
| vishwanath | 2011-08-21 14:50:37 |
| ishwar     | 2011-08-21 14:50:58 |
| ganesh     | 2011-08-31 14:50:37 |
+------------+---------------------+
3 rows in set (0.00 sec)

I'm using the following query to retrieve the records that matched interval of last 5 days but it is showing the entry of future date which is ganesh | 2011-08-31 14:50:37

  mysql> select name,mydate from persondb
      -> where date_sub(now(),INTERVAL 5 DAY)<=mydate;

Can anybody tell me the reason behind this ?

Upvotes: 1

Views: 110

Answers (1)

Jacob
Jacob

Reputation: 43209

SELECT name,mydate FROM persondb
WHERE mydate BETWEEN DATE_SUB(NOW(),INTERVAL 5 DAY) AND NOW();

The reason your query shows dates in the future is because you check if mydate is later or equal to 5 days ago. The date 2011-08-31 14:50:37 fullfils this requirement. You can use BETWEEN to check if it is in the range between now and 5 days ago.

Upvotes: 4

Related Questions