遇到類似 #1054 - Unknown column 'guaranteed_postcode' in 'IN/ALL/ANY subquery'
的 MySQL 查詢錯誤? 當您嘗試在 guaranteed_postcode
子句中使用列別名(如下面範例中的 WHERE
)時,通常會發生這種情況。
這是有問題的查詢:
<code class="language-sql">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 ( SELECT `postcode` FROM `postcodes` WHERE `region` IN ('australia') )</code>
根本原因? MySQL 的 WHERE
子句在定義別名的 子句之前處理 。 因此,在 SELECT
子句執行期間尚未識別別名 guaranteed_postcode
。 WHERE
子句中不允許使用列別名。 這是源自於查詢執行順序的限制。 WHERE
SUBSTRING
子句的子查詢中:WHERE
<code class="language-sql">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 ( SELECT `postcode` FROM `postcodes` WHERE `region` IN ('australia') )</code>
HAVING
設計用於在 HAVING
聚合之後過濾 ,而不是用於基本行過濾。 這需要重構查詢。 請參閱比較 和 WHERE
的其他資源以取得詳細說明。 HAVING
子句的範圍內應用別名計算來直接解決該問題。 除非要執行聚合,否則請避免使用 WHERE
。 HAVING
以上是為什麼不能在 MySQL WHERE 子句中使用列別名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!