如何根据具体年份显示年龄?

时间:2014-08-25 15:11:54

标签: mysql sql

我试图根据特定的年龄等级显示年龄。

以下是demo

CREATE TABLE clients
(date_birth date, date_anniversary date);

INSERT INTO clients
(date_birth, date_anniversary)
VALUES
('1991-01-04',NULL ),
('1992-01-05',NULL ),
('1993-01-06',NULL ),
('1994-01-07',NULL ),
('1995-01-08',NULL ),
('1996-01-09',NULL ),
('1997-01-10',NULL ),
('1998-01-11',NULL ),
('1999-08-12',NULL ) ;

这是查询,它显示所有转换的年龄。

SET @start:='0'; 
SET @end:='22';

SELECT YEAR(CURDATE())- year(date_birth) AS ages
FROM clients

我试图显示0到22之间的年龄,我试过这个demo

SET @start:='0'; 
SET @end:='22';

SELECT YEAR(CURDATE())- year(date_birth) AS ages
FROM clients
WHERE year(date_birth) >= @start AND year(date_birth) <= @end

请有人可以帮助我或建议我吗?

提前致谢。

3 个答案:

答案 0 :(得分:3)

您的查询应该是

SELECT YEAR(CURDATE())- year(date_birth) AS ages
FROM clients
WHERE date_birth <= (curdate() - interval @start year) 
and date_birth >= (curdate() - interval @end year)

这将在date_birth上使用你的索引(如果有的话)。

答案 1 :(得分:2)

将您的查询更改为:

SET @start:='0'; 
SET @end:='22';

SELECT YEAR(CURDATE())- year(date_birth) AS ages
FROM clients
WHERE YEAR(CURDATE())- year(date_birth) >= @start 
  AND YEAR(CURDATE())- year(date_birth) <= @end

答案 2 :(得分:1)

我更喜欢在查询中使用您不必重置它们的变量

SELECT YEAR(CURDATE())- year(date_birth) AS ages
FROM clients
CROSS JOIN(SELECT @start := 0, @end := 22)t
HAVING ages BETWEEN @start AND @end

DEMO