在 MySQL 查询的 WHERE 子句中使用列别名会产生错误

Using column alias in WHERE clause of MySQL query produces an error(在 MySQL 查询的 WHERE 子句中使用列别名会产生错误)
本文介绍了在 MySQL 查询的 WHERE 子句中使用列别名会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在运行的查询如下,但是我收到此错误:

<块引用>

#1054 - 'IN/ALL/ANY 子查询'中的未知列'guaranteed_postcode'

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`从 `users` LEFT OUTER JOIN `locations`ON `users`.`id` = `locations`.`user_id`WHERE `guaranteed_postcode` NOT IN #这是使用假冒号的地方(SELECT `postcode` FROM `postcodes` WHERE `region` IN('澳大利亚'))

我的问题是:为什么我不能在同一个数据库查询的 where 子句中使用假列?

解决方案

您只能在 GROUP BY、ORDER BY 或 HAVING 子句中使用列别名.

<块引用>

标准 SQL 不允许您引用 WHERE 中的列别名条款.强加了这个限制因为当 WHERE 代码是已执行,列值可能尚未确定.

复制自 MySQL 文档

正如评论中所指出的,改用 HAVING 可能会完成这项工作.请务必阅读此问题:WHERE vs HAVING.

The query I'm running is as follows, however I'm getting this error:

#1054 - Unknown column 'guaranteed_postcode' in 'IN/ALL/ANY subquery'

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE `guaranteed_postcode` NOT IN #this is where the fake col is being used
(
 SELECT `postcode` FROM `postcodes` WHERE `region` IN
 (
  'australia'
 )
)

My question is: why am I unable to use a fake column in the where clause of the same DB query?

解决方案

You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.

Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

Copied from MySQL documentation

As pointed in the comments, using HAVING instead may do the work. Make sure to give a read at this question too: WHERE vs HAVING.

这篇关于在 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 查询中包含缺失的月份)