Unknown Column In Where Clause

2019-01-01 03:38发布

I have a simple query:

SELECT u_name AS user_name FROM users WHERE user_name = "john";

I get Unknown Column 'user_name' in where clause. Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'?

18条回答
伤终究还是伤i
2楼-- · 2019-01-01 04:21

Unknown column in WHERE clause caused by lines 1 and 2 and resolved by line 3:

  1. $sql = "SELECT * FROM users WHERE username =".$userName;
  2. $sql = "SELECT * FROM users WHERE username =".$userName."";
  3. $sql = "SELECT * FROM users WHERE username ='".$userName."'";
查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 04:21

I had the same problem, I found this useful.

mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'");

remember to put $user in ' ' single quotes.

查看更多
步步皆殇っ
4楼-- · 2019-01-01 04:24

corrected:

SELECT u_name AS user_name FROM users WHERE u_name = 'john';
查看更多
听够珍惜
5楼-- · 2019-01-01 04:25

While you can alias your tables within your query (i.e., "SELECT u.username FROM users u;"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned.

查看更多
旧时光的记忆
6楼-- · 2019-01-01 04:26

See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html

"A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses."

(...)

It is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section B.5.4.4, “Problems with Column Aliases”.

查看更多
孤独总比滥情好
7楼-- · 2019-01-01 04:31

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred.

查看更多
登录 后发表回答