如何计算MYSQL的年龄?

时间:2017-05-02 06:52:22

标签: mysql

TABLE:

ID    pet_aggg    pet_year    pet_month    pet_date
1     birth       0           0            02/03/2017
2     birth       0           0            05/02/2017
3     birth       0           0            12/01/2017
4     age         10          6            0
5     age         6           8            0

我想计算宠物年龄少于4个月的所有宠物。

查询:

SELECT count("*") as Total 
FROM `pet_info` 
CASE WHEN `pet_info` == 'birth' 
    THEN `pet_date` HAVING BETWEEN >= '02/01/2017' AND <= '02/05/2017' 
CASE WHEN `pet_info` == 'birth' 
    THEN `pet_month` HAVING <= 4;

在我的新查询中,我想选择宠物少于4个月的所有数据。

SELECT * FROM `pet_info` 
CASE WHEN `pet_info` == 'birth' 
    THEN WHERE `pet_date` BETWEEN >= '02/01/2017' AND <= '02/05/2017' 
CASE WHEN `pet_info` == 'birth' 
    THEN WHERE `pet_month` <= 4;

2 个答案:

答案 0 :(得分:0)

WHERE条件CASE应该是这样的

SELECT * FROM pet_info 
where ( CASE WHEN pet_info = 'birth'
             THEN pet_date BETWEEN '02/01/2017' AND '02/05/2017' 
             WHEN pet_info = 'age' THEN pet_month <= 4  END); 

答案 1 :(得分:0)

基本语法有很多问题。 SQL查询(简化)的语法是:

SELECT some cols
FROM tableName
WHERE conditions

您没有将WHERE放在CASE表达式中。如果您使用BETWEEN,则不会写>=<= - x BETWEEN y AND zx >= y AND x <= z的缩写。

您遇到的另一个问题是您的日期格式不正确,无法进行比较。如果您执行pet_date BETWEEN '02/01/2017' AND <= '02/05/2017',则日期02/03/2016将与之匹配,因为它正在进行字典比较,而不是日期比较。您应该将该列更改为DATE数据类型而不是CHAR。如果您不能这样做,则应使用STR_TO_DATE()将其转换为比较日期。

然后查询应为:

SELECT *
FROM pet_info
WHERE (pet_aggg = 'birth' AND STR_TO_DATE(pet_date, '%d/%m/%Y') BETWEEN '2017-01-02' AND '2017-05-02')
   OR (pet_aggg = 'age' AND pet_month <= 4)

而不是将特定日期放入查询中,您只需使用STR_TO_DATE(pet_date, '%d/%m/%Y') >= DATE_SUB(NOW(), INTERVAL 4 MONTH)

即可