我正在运行的查询如下所示,但是我得到了这个错误:
#1054 -‘in /ALL/ANY子查询’中的未知列'guaranteed_postcode‘
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'
)
)
我的问题是:为什么我不能在同一个DB查询的where子句中使用假列?
发布于 2009-06-03 00:38:20
只能在GROUP BY、ORDER BY或HAVING子句中使用列别名。
标准SQL不允许在WHERE子句中引用列别名。之所以施加此限制,是因为在执行WHERE代码时,可能尚未确定列值。
正如评论中指出的,使用HAVING可能会做这项工作。一定要仔细阅读这个问题:WHERE vs HAVING。
发布于 2009-06-03 00:47:10
正如维克多指出的,问题出在别名上。但是,通过将表达式直接放入WHERE x IN y子句中,可以避免这种情况:
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 SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
然而,我猜这是非常低效的,因为必须为外部查询的每一行执行子查询。
发布于 2012-07-27 18:14:13
标准SQL (或MySQL)不允许在WHERE子句中使用列别名,因为
计算WHERE子句时,可能尚未确定列值。
(来自MySQL documentation)。您可以做的是计算WHERE子句中的列值,将值保存在变量中,并在字段列表中使用它。例如,您可以这样做:
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
这避免了在表达式变得复杂时重复表达式,从而使代码更易于维护。
https://stackoverflow.com/questions/942571
复制相似问题