如何在Correlated子查询中使用别名?

时间:2015-12-26 23:41:14

标签: mysql sql select

mysql> select * from instructor;

+-------+------------+------------+----------+
| ID    | name       | dept_name  | salary   |
+-------+------------+------------+----------+
| 10101 | Srinivasan | Comp. Sci. | 65000.00 |
| 12121 | Wu         | Finance    | 90000.00 |
| 15151 | Mozart     | Music      | 40000.00 |
| 22222 | Einstein   | Physics    | 95000.00 |
| 32343 | El Said    | History    | 60000.00 |
| 33456 | Gold       | Physics    | 87000.00 |
| 45565 | Katz       | Comp. Sci. | 75000.00 |
| 58583 | Califieri  | History    | 62000.00 |
| 76543 | Singh      | Finance    | 80000.00 |
| 76766 | Crick      | Biology    | 72000.00 |
| 83821 | Brandt     | Comp. Sci. | 92000.00 |
| 98345 | Kim        | Elec. Eng. | 80000.00 |
+-------+------------+------------+----------+

我有一个像这样的SQL语句

select name,salary,dept_name from instructor t1 
where salary > 
(
   select avg(salary) 
   from instructor t2
   group by dept_name   
   having t1.dept_name = t2.dept_name 
)
+-----------+----------+------------+
| name      | salary   | dept_name  |
+-----------+----------+------------+
| Wu        | 90000.00 | Finance    |
| Einstein  | 95000.00 | Physics    |
| Califieri | 62000.00 | History    |
| Brandt    | 92000.00 | Comp. Sci. |
+-----------+----------+------------+

我想在外部查询中添加别名(dept_avg_salary),但失败了......

select name,salary,dept_name,dept_avg_salary from instructor t1 
where salary > 
(
   select avg(salary) as dept_avg_salary
   from instructor t2
   group by dept_name
   having t1.dept_name = t2.dept_name 
) 
  

ERROR 1054(42S22):'字段列表'中的未知列'dept_avg_salary'

任何人都可以告诉我为什么,非常感谢你!

1 个答案:

答案 0 :(得分:1)

你不能像这样引用别名。这是使用带有join的子查询的更好方法:

select t1.name, t1.salary, t1.dept_name, t2.dept_avg_salary
from instructor t1 join (
    select dept_name, avg(salary) dept_avg_salary
    from instructor
    group by dept_name) t2 on t1.dept_name = t2.dept_name
where t1.salary > t2.dept_avg_salary