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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:15:34  来源:igfitidea点击:

MySQL - SELECT AS in WHERE

mysqlsqlselect

提问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 ALIASon the WHEREclause. You shoul be using the column,

首先,不能使用ALIASonWHERE子句。你应该使用专栏,

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 ALIAStakes place on the SELECTclause which is before the WHEREclause.

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

valis 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'