MySQL - 在 WHERE 中选择 AS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14413867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL - SELECT AS in WHERE
提问by Martin
For some reason, this doesn't work:
出于某种原因,这不起作用:
select substring(rating, instr(rating,',') +1, +2) as val
from users where val = '15';
It gives this error:
它给出了这个错误:
ERROR 1054 (42S22): Unknown column 'val' in 'where clause'
错误 1054 (42S22):“where 子句”中的未知列“val”
How do I do it then?
那我该怎么做呢?
回答by John Woo
First, you cannot use ALIAS
on the WHERE
clause. You shoul be using the column,
首先,不能使用ALIAS
onWHERE
子句。你应该使用专栏,
SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val
FROM users
WHERE SUBSTRING(rating, INSTR(rating,',') +1, +2) = '15'
The reason is as follows: the order of operation is SQL,
原因如下:操作顺序是SQL,
- FROM clause
- WHERE clause
- GROUP BY clause
- HAVING clause
- SELECT clause
- ORDER BY clause
- FROM 子句
- WHERE 子句
- GROUP BY 子句
- HAVING 子句
- SELECT 子句
- ORDER BY 子句
the ALIAS
takes place on the SELECT
clause which is before the WHERE
clause.
theALIAS
发生在该SELECT
子句之前的WHERE
子句上。
if you really want to use the alias, wrap it in a subquery,
如果您真的想使用别名,请将其包装在子查询中,
SELECT *
FROM
(
SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val
FROM users
) s
WHERE val = '15'
回答by echo_Me
val
is not defined, it's just an alias. Do it like this:
val
没有定义,它只是一个别名。像这样做:
SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val
FROM users
WHERE SUBSTRING(rating, INSTR(rating,',') +1, +2) = 15
回答by u10679283
You can use this query
您可以使用此查询
SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2)
FROM users
WHERE SUBSTRING(rating, INSTR(rating,',') +1, +2) = '15'