我需要在 WHERE 子句中使用别名,但它一直告诉我它是一个未知列。有没有办法解决这个问题?我需要选择评级高于 x 的记录。评分计算为以下别名:
sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating
最佳答案
您可以使用 HAVING 子句,它可以看到别名,例如
HAVING avg_rating>5
但是在 where 子句中你需要重复你的表达,例如
WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))>5
但是!并非所有表达式都被允许 - 使用像 SUM 这样的聚合函数将不起作用,在这种情况下,您需要使用 HAVING 子句。
来自 MySQL Manual :
It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section B.1.5.4, “Problems with Column Aliases”.
关于mysql - 你可以在mysql的WHERE子句中使用别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/200200/