Home >Database >Mysql Tutorial >Why Does My SQL Query Fail with 'Unknown Column In Where Clause' When Using Aliases?
Question:
Queries using aliases in the SELECT statement will cause an error, prompting an unknown alias column in the WHERE statement. For example, the following query triggers this error:
<code class="language-sql">SELECT u_name AS user_name FROM users WHERE user_name = "john";</code>
Explanation:
The execution order of SQL is from right to left. In this example, the WHERE clause is executed before the SELECT clause. Therefore, when the WHERE clause is parsed, the alias user_name
has not been defined yet.
Solution:
To solve this problem, you can use the original column names in the WHERE clause:
<code class="language-sql">SELECT u_name AS user_name FROM users WHERE u_name = "john";</code>
Or enclose the alias column name in parentheses in the WHERE clause:
<code class="language-sql">SELECT u_name AS user_name FROM users WHERE (user_name = "john");</code>
The above is the detailed content of Why Does My SQL Query Fail with 'Unknown Column In Where Clause' When Using Aliases?. For more information, please follow other related articles on the PHP Chinese website!