SQL学习笔记——关联子查询(基本使用,查询语句,执行顺序,使用别名和不使用别名的区别)

在进一步细分的组内进行比较时,需要使用关联子查询。

表记录:

+------------+--------------+--------------+------------+
| 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语句总是成立的,算的也是所有商品的平均值。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值