我正在运行的查询如下,但我得到这个错误:

未知列'guaranteed_postcode'在' in /ALL/ANY子查询'

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子句中使用假列?


当前回答

你可以使用SUBSTRING(locations.raw,-6,4)作为where条件

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'
)
)

其他回答

你可以使用SUBSTRING(locations.raw,-6,4)作为where条件

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'
)
)

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

标准SQL不允许这样做 引用WHERE中的列别名 条款。这个限制是强加的 因为WHERE代码是 执行后,列值可能还没有 是确定的。

从MySQL文档复制

正如评论中指出的那样,使用HAVING可能会起到作用。一定要读一下这个问题:WHERE和HAVING。

您可以使用HAVING子句在SELECT字段和别名中计算过滤器

正如维克多指出的,问题出在别名上。不过,可以通过将表达式直接放入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'
 )
)

但是,我认为这是非常低效的,因为必须对外部查询的每一行执行子查询。

也许我的回答太晚了,但这可以帮助其他人。

您可以用另一个select语句将其括起来,并对其使用where子句。

SELECT * FROM (Select col1, col2,...) as t WHERE t.calcAlias > 0

calcAlias是计算的别名列。