0

为什么第一个 SQL 语句不执行,而第二个执行?

1.

select e.employee_id, e.last_name, e.salary as "SALARY"
from employees e
where employees.salary > (select avg(salary) from employees) 
order by SALARY;

2.

select e.employee_id, e.last_name, e.salary as "SALARY"
from employees e
where e.salary > (select avg(salary) from employees) 
order by SALARY;
4

2 回答 2

5

因为您已经为表名定义了别名employee

因此,在WHERE子句中,您需要使用别名,而不是表名,因为它不再有效。

SELECT e.employee_id, e.last_name, e.salary as "SALARY" 
FROM   employees e 
WHERE  e.salary > (select avg(salary) from employees) 
    -- ^ ALIAS should be used, not the tableName
ORDER  BY SALARY;

这可能有点离题,但这是一个附加信息。

SQL操作的顺序如下:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句

由于您在子句中为表名提供了别名,FROM因此按照操作顺序的任何内容现在都指的是给定的别名,而不是表名本身。

于 2013-03-30T03:30:21.460 回答
0

为了使第一个工作,用员工替换所有出现的“e”并删除“e”别名:

select employees.employee_id, employees.last_name, employees.salary as "SALARY"
from employees 
where employees.salary > (select avg(salary) from employees) 
order by SALARY;
于 2013-03-30T03:54:14.517 回答