如何确定MySQL中的人是否超过21岁

时间:2016-11-08 18:39:29

标签: mysql sql

我正在尝试在MySQL中创建一个视图。我希望它显示用户电子邮件,first-lastname,他们的DOB以及他们当前的年龄。我只想向21岁以上的用户展示。

这就是我所拥有的:

CREATE VIEW 'valid_Users' AS 
SELECT Persons.Email AS Email, Persons.FName + ' ' + Persons.LName AS Name,  Persons.DOB AS Birth_Date, DATEDIFF(Persons.DOB, NOW()) AS Current_Age'
FROM Persons
WHERE DATEDIFF(Persons.DOB, NOW()) > 21;

问题是Where子句返回一个负数,这显然不是一个正确的年龄。我如何编辑此代码以确定一个人的正确年龄?

我知道名字还不起作用 - 但是......这里是一些当前数据的图像。实际的表格是'用户'

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试:

CREATE VIEW 'valid_Users' AS 
SELECT Persons.Email AS Email, Persons.FName + ' ' + Persons.LName AS Name, Persons.DOB AS Birth_Date, DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), Persons.DOB)), "%Y")+0 AS Current_Age'
FROM Persons
WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), Persons.DOB)), "%Y")+0 > 21;

OR:

CREATE VIEW 'valid_Users' AS 
SELECT Persons.Email AS Email, Persons.FName + ' ' + Persons.LName AS Name, Persons.DOB AS Birth_Date, TIMESTAMPDIFF(YEAR, Persons.DOB, NOW()) AS Current_Age'
FROM Persons
WHERE TIMESTAMPDIFF(YEAR, Persons.DOB, NOW()) > 21;

答案 1 :(得分:0)

我认为你想要这样的东西:

CREATE VIEW valid_Users AS 
    SELECT p.Email, 
           CONCAT(p.FName, ' ', p.LName) AS Name,  
           p.DOB AS BirthDate,
           TIMESTAMPDIFF('year', p.DOB, CURDATE()) AS CurrentAge
    FROM Persons p
    WHERE p.DOB < CURDATE() - INTERVAL 21 YEARS;

答案 2 :(得分:0)

试试切换参数:

SELECT DATEDIFF(NOW(), Persons.DOB) AS days; 

告诉我们你得到了什么?