Can you use an alias in the WHERE clause in mysql?(你可以在mysql的WHERE子句中使用别名吗?)
问题描述
我需要在 WHERE 子句中使用别名,但它一直告诉我它是一个未知列.有没有办法解决这个问题?我需要选择评级高于 x 的记录.评分计算为以下别名:
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
推荐答案
你可以使用 HAVING 子句,可以看到别名,例如
You could use a HAVING clause, which can see the aliases, e.g.
HAVING avg_rating>5
但是在 where 子句中你需要重复你的表达,例如
but in a where clause you'll need to repeat your expression, e.g.
WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))>5
但是!并非所有表达式都被允许 - 使用像 SUM 这样的聚合函数将不起作用,在这种情况下,您需要使用 HAVING 子句.
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.
来自 MySQL 手册:
不允许引用WHERE 子句中的列别名,因为列值可能还没有当 WHERE 子句被确定被执行.请参阅 第 B.1.5.4 节,列别名问题".
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的WHERE子句中使用别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你可以在mysql的WHERE子句中使用别名吗?


基础教程推荐
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在多列上分布任意行 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01