一道多表更新的面试题

问题:有t_product产品表(编号,名称,价格,类别),有些编号的商品名称相同。
要求:将各同商品名称相同的,改为该商品的平均价格
select t.* from t_product t

P_ID P_NAME P_PRICE P_TYPE
1 商品a 2.00 t1
2 商品b 2.00 t2
3 商品c 3.00 t3
4 商品a 4.00 t4
5 商品b 4.00 t5


--★将各同商品名称相同的,改为该商品的平均价格

oracle中的写法
update t_product t set t.p_price=
(
select avg(a.p_price)
from t_product a
where t.p_name=a.p_name
group by a.p_name
)

sqlServer:

update t_product  set p_price=
(
select avg(a.p_price)
from t_product a
where t_product.p_name=a.p_name
group by a.p_name
);不能使用表别名

mysql中暂时没成功

更新以后:
select t.* from t_product t
P_ID P_NAME P_PRICE P_TYPE
1 商品a 3.00 t1
2 商品b 3.00 t2
3 商品c 3.00 t3
4 商品a 3.00 t4
5 商品b 3.00 t5


--分析过程:
select t.p_name from t_product t
--外部查询返回:
P_NAME
商品a
商品b
商品c
商品a
商品b


--针对于外部查询的每一行,分别执行:
P_NAME
商品a
select avg(a.p_price) from t_product a
where a.p_name='商品a'
group by a.p_name
商品b
select avg(a.p_price) from t_product a
where a.p_name='商品b'
group by a.p_name
商品c
商品a
商品b


--多表更新语法小结:
update ? set ?=(
  select ? from ?
  where 连接条件
)


--子查询规律最强总结:
--外部一个查询,内部一个查询,内部查询再跟一个连接条件。

你可能感兴趣的:(oracle,C++,c,mysql,面试)