3.8.7 标量子查询

3.8.7 标量子查询

SQL允许子查询出现在返回单个值的表达式能够出现的任何地方,只要该子查询只返回包含单个属性的单个元组;这样的子查询称为标量子查询(scalar subquery)
例如,一个子查询可以用到下面例子的select子句中,这个例子列出所有的系以及它们拥有的教师数

1
2
3
4
5
select dept_name,(
select count(*)from instructor
where department.dept_name=instructor.dept_name
) as num_instructors
from department;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mysql> select dept_name,(
select count(*)from instructor
where department.dept_name=instructor.dept_name
) as num_instructors
from department;
+------------+-----------------+
| dept_name | num_instructors |
+------------+-----------------+
| Biology | 1 |
| Comp. Sci. | 3 |
| Elec. Eng. | 1 |
| Finance | 2 |
| History | 2 |
| Music | 1 |
| Physics | 2 |
+------------+-----------------+
7 rows in set

上面例子中的子查询保证只返回单个值,因为它使用了不带group bycount(*)聚集函数。此例也说明了对相关变量的使用,即使用在外层查询的from子句中关系的属性,例如上例中的department.dept_name;

标量子查询可以出现在selectwherehaving子句中。也可以不使用聚集函数来定义标量子查询。在编译时并非总能判断一个子査询返回的结果中是否有多个元组,如果在子査询被执行后其结果中有不止一个元组,则产生一个运行时错误。
注意从技术上讲标量子查询的结果类型仍然是关系,尽管其中只包含单个元组。然而,当在表达式中使用标量子查询时,它出现的位置是单个值出现的地方,SQL就从该关系中包含单属性的单元组中取出相应的值,并返回该值。