子查询:
就是一个查询的结果,可以作为另一个查询的数据源或者条件
注意:
组函数不能嵌套
例如:
如何查询book表中最贵的书的书名:
此处可查询条件: 书名 价格 最大价格
法一:
将查询结果作为另一个查询的条件:
例:
select name,price from book where price = (select max(price) from book);
法二:
等值比较 关键字 in
select name,price from book where price in(select max(price) from book where price);
例:
此处提供一张book表,表中有如下 数据:
num
name
price
sell
type
1120
test-1
10
yes
S
1150
test-2
13
no
S
1122
test-3
20
no
T
1125
test-4
23
yes
T
在外面查询中,查询的结果作为另一个查询的数据源时,需要将其当成一张表,在当成表的过程中,必须起别名;
例:
select max(avg_price) from (select avg(price) avg_price,type from book group by type) avg_table;
此处结尾处 的 avg_table 就是一个别名,根据需求自定义
平均price最大的type:(此处比较绕,请耐心分析)
select avg_price,type from (select avg(price) avg_price,type from book group by type) e where avg_price = (select max(avg_price) from (select avg(price) avg_price,type from book group by type) avg_table);
此处的 e 是一个表的别名