mysql 的 WHERE 子句中可以使用别名吗?
我需要在 WHERE 子句中使用别名,但它一直告诉我它是一个未知列。 有什么办法可以解决这个问题吗? 我需要选择评级高于 x 的记录。 评级按以下别名计算:
sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating
I need to use an alias in the WHERE clause, but It keeps telling me that its an unknown column. Is there any way to get around this issue? I need to select records that have a rating higher than x. Rating is calculated as the following alias:
sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 HAVING 子句,它可以看到别名,例如,
但在 where 子句中,您需要重复表达式,例如
BUT! 并非所有表达式都被允许 - 使用 SUM 这样的聚合函数将不起作用,在这种情况下,您需要使用 HAVING 子句。
来自 MySQL 手册:
You could use a HAVING clause, which can see the aliases, e.g.
but in a where clause you'll need to repeat your expression, e.g.
BUT! Not all expressions will be allowed - using an aggregating function like SUM will not work, in which case you'll need to use a HAVING clause.
From the MySQL Manual:
我不知道这在 mysql 中是否有效,但是使用 sqlserver 你也可以像这样包装它:
I don't know if this works in mysql, but using sqlserver you can also just wrap it like:
这个问题已经很老了,一个答案已经获得了 160 票......
不过我还是要澄清这一点:问题实际上不是关于是否可以在
WHERE
条款。是一个聚合。 在
WHERE
子句中,我们通过查看表中的值来限制我们想要的记录。 然而,sum(reviews.rev_ rating) 和 count(reviews.rev_id) 并不是我们在记录中找到的值; 它们是我们只有在汇总记录后才能获得的值。所以
WHERE
是不合适的。 我们需要HAVING
,因为我们想在聚合后限制结果行。 不可能是这样,也
不可能是这样。
另一方面是可能的并且符合SQL标准。 而
只能在 MySQL 中实现。 根据标准,它不是有效的 SQL,因为
SELECT
子句应该在HAVING
之后执行。 来自 MySQL 文档:https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
This question is quite old and one answer already gained 160 votes...
Still I would make this clear: The question is actually not about whether alias names can be used in the
WHERE
clause.is an aggregation. In the
WHERE
clause we restrict records we want from the tables by looking at their values.sum(reviews.rev_rating)
andcount(reviews.rev_id)
, however, are not values we find in a record; they are values we only get after aggregating the records.So
WHERE
is inappropriate. We needHAVING
, as we want to restrict result rows after aggregation. It can't benor
hence.
on the other hand is possible and complies with the SQL standard. Whereas
is only possible in MySQL. It is not valid SQL according to the standard, as the
SELECT
clause is supposed to get executed afterHAVING
. From the MySQL docs:https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
如果您的查询是静态的,您可以将其定义为视图,然后在查询视图时可以在 where 子句中使用该别名。
If your query is static, you can define it as a view then you can use that alias in the where clause while querying the view.