如何使用MySQL在别名列上使用WHERE条件进行选择?

时间:2012-12-11 05:11:36

标签: mysql sql

我有以下查询:

SELECT IF(TIMESTAMPDIFF(HOUR,users_codes.timestam,CURRENT_TIMESTAMP()) < 48,'no','yes') AS Expired
FROM users_codes

如何仅返回'no'

的行

2 个答案:

答案 0 :(得分:6)

添加WHERE条件。 您不能在where子句上使用ALIAS

SELECT IF(TIMESTAMPDIFF(HOUR,users_codes.timestam,CURRENT_TIMESTAMP()) < 48,'no','yes') AS Expired 
FROM   users_codes
WHERE  IF(TIMESTAMPDIFF(HOUR,users_codes.timestam,CURRENT_TIMESTAMP()) < 48,'no','yes') = 'no'

或使用子查询

SELECT *
FROM
(
    SELECT IF(TIMESTAMPDIFF(HOUR,users_codes.timestam,CURRENT_TIMESTAMP()) < 48,'no','yes') AS Expired 
    FROM   users_codes
) s
WHERE  Expired  = 'no'

答案 1 :(得分:2)

我相信你可以做这样的事情

SELECT IF( TIMESTAMPDIFF(
    HOUR,
    users_codes.timestam,
    CURRENT_TIMESTAMP()
  ) < 48, 'no', 'yes') AS Expired

FROM users_codes
HAVING Expired = 'no';