我有简单的SQL:
SELECT TIMESTAMPDIFF(YEAR, bdate, CURDATE()) as age, id, bdate
from my_table
where age between 20 and 30
我收到了这个错误:
未知列'年龄'在' where子句'
答案 0 :(得分:2)
您无法在where clause
中使用别名,您需要在where子句中重用别名的公式或使用having clause
或使用外部查询
SELECT TIMESTAMPDIFF(YEAR, bdate, CURDATE()) as age, id, bdate
from my_table
having age between 20 and 30
OR
select * from (
SELECT TIMESTAMPDIFF(YEAR, bdate, CURDATE()) as age, id, bdate
from my_table
)x
where age between 20 and 30
答案 1 :(得分:1)
MySQL中的WHERE
子句中没有别名。
标准SQL不允许在WHERE子句中引用列别名。强制执行此限制是因为在评估WHERE子句时,可能尚未确定列值。 的 MySQL Docs 强>
你必须使用
WHERE TIMESTAMPDIFF(YEAR, bdate, CURDATE()) BETWEEN 20 AND 30