在进一步细分的组内进行比较时,需要使用关联子查询。
表记录:
+------------+--------------+--------------+------------+
| product_id | product_name | product_type | sale_price |
+------------+--------------+--------------+------------+
| 0001 | T恤衫 | 衣服 | 1000 |
| 0002 | 打孔器 | 办公用品 | 500 |
| 0003 | 运动T恤 | 衣服 | 4000 |
| 0004 | 菜刀 | 厨房用具 | 3000 |
| 0005 | 高压锅 | 厨房用具 | 6800 |
| 0006 | 叉子 | 厨房用具 | 500 |
| 0007 | 擦菜板 | 厨房用具 | 880 |
| 0008 | 圆珠笔 | 办公用品 | 100 |
+------------+--------------+--------------+------------+
查询语句:按照 商品种类对平均销售单价进行比较,选出大于本类型商品平均值的商品。
select product_type, product_name, sale_price
from product as P1
where sale_price > (select avg(sale_price)
from product as P2
where P1.product_type = P2.product_type);
查询结果:
+--------------+------------+
| product_name | sale_price |
+--------------+------------+
| 打孔器 | 500 |
| 运动T恤 | 4000 |
| 菜刀 | 3000 |
| 高压锅 | 6800 |
+--------------+------------+
先执行外层的 select 语句的 from,把 product 表里面每行数据查询出来,查询每一行数据,都要执行一次内层 select 语句,这个时候是完整的执行内层 select 语句。在执行子查询时,where语句将与外层查询相同的product_type筛选出来,也就是相同类型的商品,然后求其平均值,再执行外层的where语句。外层查询一行数据后,进入子查询,查完后,外层查询下一行数据,再进入子查询,直到结束,所有的数据都被查询一遍。
在不使用别名的情况下:
查询语句:
select product_type, product_name, sale_price
from product
where sale_price > (select avg(sale_price)
from product
where product_type = product_type);
查询结果:
+--------------+--------------+------------+
| product_type | product_name | sale_price |
+--------------+--------------+------------+
| 衣服 | 运动T恤 | 4000 |
| 厨房用具 | 菜刀 | 3000 |
| 厨房用具 | 高压锅 | 6800 |
+--------------+--------------+------------+
在不使用别名的情况下,子查询使用的都是自己从product表中选出的数据,这种情况下,where语句总是成立的,算的也是所有商品的平均值。