日期:2014-05-16  浏览次数:20399 次

Oracle数据库高级查询(四)子查询和连接查询的综合案例

查询出高于本类商品平均价格的商品类别id,商品id,商品名称,价格,库存量

1.确定要查询的数据以及数据来源

select sort_id,id,name,price,stockcount from es_product

where price>(本类商品平均价格)


2.每类商品平均价格如下

(select sort_id,avg(price) avgprice from es_product

group by sort_id)b

select * from es_product a;


3.将a和b进行连接查询,条件:a.sort_id=b.sort_id同时a.price>b.avgprice

select a.sort_id,id,name,price,stockcount from es_product a  ,

(select sort_id,avg(price) avgprice from es_product

group by sort_id)b

where a.sort_id=b.sort_id and a.price>b.avgprice


需要注意的是

当使用from 子句中使用子查询时,子查询将被作为虚拟表(视图)对待,该虚拟表接下来需要使用时,

必须给该子查询指定别名