整张表数据:
+------------+--------------+--------------+------------+
| 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
where sale_price > (select avg(sale_price)
from product
where product_type = product_type);
查询结果:
+--------------+--------------+------------+
| product_type | product_name | sale_price |
+--------------+--------------+------------+
| 衣服 | 运动T恤 | 4000 |
| 厨房用具 | 菜刀 | 3000 |
| 厨房用具 | 高压锅 | 6800 |
+--------------+--------------+------------+
使用别名进行查询:
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_type | product_name | sale_price |
+--------------+--------------+------------+
| 办公用品 | 打孔器 | 500 |
| 衣服 | 运动T恤 | 4000 |
| 厨房用具 | 菜刀 | 3000 |
| 厨房用具 | 高压锅 | 6800 |
+--------------+--------------+------------+
就很懵,因为是初学,所以不明白是什么原因,还是希望有人帮忙指点一下
第一个查询里面,没有表别名,子查询中两个字段都取自子查询的 product 表;
第二个查询,有表别名,子查询中的 where 子句是比较的内外两个表。
看你的需要,应该是要第二个。
https://blog.csdn.net/qq_25186987/article/details/53695319
不加别名,你第一个查询查询的是先查子查询出来的数据,然后from子查询的数据,加了别名,你第二个查询就是有明确的指向性了
第一个里的product_type = product_type就跟1=1是一个意思