为什么这些SQL语句中只有一个有效?

时间:2013-03-30 03:28:53

标签: sql oracle select

为什么第一个SQL语句没有执行,第二个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;

2 个答案:

答案 0 :(得分: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;

这可能是一个 off-topic ,但这是一个额外的信息。

SQL操作顺序如下:

  • FROM clause
  • WHERE子句
  • GROUP BY子句
  • HAVING条款
  • SELECT条款
  • ORDER BY子句

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

答案 1 :(得分: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;
相关问题