如何计算SQL查询中用户的年龄。请注意,我将数据库拆分为以下字段:birthday,birthmonth和birthyear。
我创建了fiddle以显示我的意思。
CREATE TABLE IF NOT EXISTS `user_profile` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_birthday` tinyint(4) NOT NULL,
`user_birthmonth` tinyint(4) NOT NULL,
`user_birthyear` smallint(6) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `user_profile`
(user_birthday, user_birthmonth, user_birthyear) VALUES (31, 12, 1990)
答案 0 :(得分:1)
<强> SqlFiddleDemo 强>
SELECT YEAR(NOW()) - YEAR(birthday) - (DATE_FORMAT(birthday, '%m%d') < DATE_FORMAT(NOW(), '%m%d')) AS Age
FROM (
SELECT
CAST(CONCAT(`user_birthyear`, '-', `user_birthmonth`, '-', `user_birthday`) AS DATE) AS birthday
FROM user_profile ) AS s
答案 1 :(得分:-3)
年(getdate()) - birthyear就够了