你可以在 mysql 的 WHERE 子句中使用别名吗?

Can you use an alias in the WHERE clause in mysql?(你可以在 mysql 的 WHERE 子句中使用别名吗?)
本文介绍了你可以在 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 子句中使用别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)