MySQL Forums
Forum List  »  Newbie

Re: Query for 3 months back
Posted by: Barry Galbraith
Date: January 08, 2013 03:04PM

Ah!!! There's your problem. Your dte field looks like its a VARCHAR type.
If you want to do date arithmetic it has to be a DATE type.

Consider this.
/*Table structure for table `test1` */

DROP TABLE IF EXISTS `test1`;

CREATE TABLE `test1` (
  `id` int(11) NOT NULL,
  `dte` varchar(20) DEFAULT NULL,
  `real_date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*Data for the table `test1` */

insert  into `test1`(`id`,`dte`,`real_date`)
 values (1,'9/1/2012','2012-01-09')
 ,(2,'9/9/2012','2012-09-09')
 ,(3,'10/1/2012','2012-10-01')
 ,(4,'10/9/2012','2012-10-09')
 ,(5,'10/7/2012','2012-10-07')
 ,(6,'11/7/2012','2012-11-07')
 ,(7,'11/7/2012','2012-11-07')
 ,(8,'10/8/2012','2012-10-08')
 ,(9,'1/10/2012','2012-01-10')
 ,(10,'10/10/2012','2012-10-10')
 ,(11,'10/11/2012','2012-10-11')
 ,(12,'10/12/2012','2012-10-12')
 ,(13,'10/13/2012','2012-10-13')
 ,(14,'10/6/2012','2012-10-06')
 ;

mysql> SELECT dte
    -> , DATEDIFF( NOW( ) , real_date ) AS period
    -> , NOW( )
    -> ,real_date
    -> FROM test1
    -> WHERE DATE_SUB( NOW( ) , INTERVAL 3
    -> MONTH ) < real_date ;
+------------+--------+---------------------+------------+
| dte        | period | NOW( )              | real_date  |
+------------+--------+---------------------+------------+
| 11/7/2012  |     63 | 2013-01-09 07:59:54 | 2012-11-07 |
| 11/7/2012  |     63 | 2013-01-09 07:59:54 | 2012-11-07 |
| 10/10/2012 |     91 | 2013-01-09 07:59:54 | 2012-10-10 |
| 10/11/2012 |     90 | 2013-01-09 07:59:54 | 2012-10-11 |
| 10/12/2012 |     89 | 2013-01-09 07:59:54 | 2012-10-12 |
| 10/13/2012 |     88 | 2013-01-09 07:59:54 | 2012-10-13 |
+------------+--------+---------------------+------------+
6 rows in set (0.00 sec)
Here you have a period of 91 days, but is 3 months before today.

BTW, when I run your query I get no rows returned, not what you described.

Good luck,
Barry.

Options: ReplyQuote


Subject
Written By
Posted
January 07, 2013 12:49PM
January 07, 2013 02:40PM
January 08, 2013 09:23AM
January 08, 2013 09:26AM
Re: Query for 3 months back
January 08, 2013 03:04PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.