MySQL在where子句中引用取别名的列

备注:测试数据库版本为MySQL 8.0

如需要scott用户下建表及录入数据语句,可参考:
scott建表及录入数据sql脚本

我们写sql的过程中,经常会遇到别名的问题,也经常因为别名的问题报错
下面是一个where应用别名列的问题

-- where直接用别名列,报错
select sal as salary,co
from emp               
where salary < 5000;   
-- 用内联视图可以解决这个问题
select * 
  from (
select sal as salary,comm as commission
   from emp
       ) x
where salary < 5000;

执行结果:

mysql> select sal as salary,comm as commission
    -> from emp
    -> where salary < 5000;
ERROR 1054 (42S22): Unknown column 'salary' in 'where clause'
mysql>
mysql>
mysql>
mysql> select *
    ->   from (
    -> select sal as salary,comm as commission
    ->    from emp
    ->        ) x
    -> where salary < 5000;
+---------+------------+
| salary  | commission |
+---------+------------+
| 1600.00 |    1300.00 |
| 1250.00 |    1500.00 |
| 2975.00 |     500.00 |
| 1250.00 |    2400.00 |
| 2850.00 |     500.00 |
| 2450.00 |     500.00 |
| 3000.00 |     500.00 |
| 1500.00 |       0.00 |
| 1100.00 |     500.00 |
|  950.00 |     500.00 |
| 3000.00 |     500.00 |
| 1300.00 |     500.00 |
+---------+------------+
12 rows in set (0.01 sec)

猜你喜欢

转载自blog.csdn.net/u010520724/article/details/107937828