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

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


当前回答

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

其他回答

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

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

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

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

calcAlias是计算的别名列。

我使用mysql 5.5.24和以下代码工作:

select * from (
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`
) as a
WHERE guaranteed_postcode NOT IN --this is where the fake col is being used
(
 SELECT `postcode` FROM `postcodes` WHERE `region` IN
 (
  'australia'
 )
)

标准SQL(或MySQL)不允许在WHERE子句中使用列别名,因为

当计算WHERE子句时,可能还没有确定列值。

(来自MySQL文档)。您可以做的是计算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'
 )
)

这避免了在表达式变得复杂时重复它,使代码更容易维护。

你可以使用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'
)
)