Wednesday, November 18, 2009

Select the age from birthday date field in mysql ?

Hi,

following is user table:

CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(255) NOT NULL,
`mname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`createdat` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`birthday` date NOT NULL,
PRIMARY KEY (`id`)
);

insert one row into table:

INSERT INTO `user` (`id`, `fname`, `mname`, `lname`, `createdat`, `birthday`) VALUES

(1, ‘Anil’, ‘Kumar’, ‘Panigrahi’, ‘2009-11-19 11:04:27′, ‘1983-02-14′),

To retrieve age from the table:

SELECT YEAR( NOW( ) ) - YEAR( birthday ) - IF( MONTH( NOW( ) ) < MONTH( birthday ) , 1, 0 ) - IF( MONTH( NOW( ) ) = MONTH( birthday )AND DAYOFMONTH( NOW( ) ) < DAYOFMONTH( birthday ) , 1, 0 ) AS age, birthday, now( ) From user;
Hope that it will be useful.

Complete information @ http://anil2u.wordpress.com

No comments:

Post a Comment