1、子查询语法:
select product_type, cnt_product
from ( select product_type, count(*) as cnt_product
from Product
group by product_type ) as productSum;
--子查询是在from语句中插入select语句
--as productSum就是子查询的名称,,但该名称是一次性的,在SELECT 语句执行之后就消失了,在某些DBMS中as可以省略
select语句包含嵌套的结构,首先会执行from子句中的select语句,然后才会执行外层的select语句。
子查询的层数原则上没有限制。
原则上子查询必须设定名称(当子查询的结果是一组记录时,需要设定别名,当是一个标量时,不需要用到别名)。
2、标量子查询:
标量就是单一的意思,而标量子查询则有一个特殊的限制,那就是必须而且只能返回1行1列的结果,也就是返回表中某一行的某一列的值。能够使用常数或者列名的地方,无论是select子句、group by 子句、having子句,还是order by子句,几乎所有的地方都可以使用标量子查询。
注意;子查询绝对不能返回多行结果
--where子句不能使用聚合函数,对于“查询出销售单价高于平均销售单价的商品”可以使用子查询
select product_id, product_name, sale_price
from product
where sale_price > (select avg(sale_price)
from product);
--在select子句中使用标量子查询
select product_id,
product_name,
sale_price,
(select avg(sale_price)
from product) as avg_price
from product;
--在having子句中使用标量子查询
select product_type, avg(sale_price)
from product
group by product_type
having avg(sale_price) > (select avg(sale_price)
from product);