一道多表更新的面试题

问题:有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 连接条件
)


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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值