MySQL关联表更新数据SQL脚本

假定我们有两张表,一张表为Product表存放产品信息,其中有产品价格列Price;另外一张表是ProductPrice表,我们要将ProductPrice表中的价格字段Price更新为Price表中价格字段的80%。 
在Mysql中我们有几种手段可以做到这一点,一种是update table1 t1, table2 ts ...的方式:

UPDATE product p, productPrice pp 

SET pp.price = p.price * 0.8 

WHERE p.productId = pp.productId 

AND p.dateCreated < '2004-01-01' 

另外一种方法是使用inner join然后更新: 

UPDATE product p 

INNER JOIN productPrice pp 

扫描二维码关注公众号,回复: 226022 查看本文章

ON p.productId = pp.productId 

SET pp.price = pp.price * 0.8 

WHERE p.dateCreated < '2004-01-01' 

另外我们也可以使用left outer join来做多表update,比方说如果ProductPrice表中没有产品价格记录的话,将Product表的isDeleted字段置为1,如下sql语句: 

UPDATE product p 

LEFT JOIN productPrice pp 

ON p.productId = pp.productId 

SET p.deleted = 1 

WHERE pp.productId IS null 

另外,上面的几个例子都是两张表之间做关联,但是只更新一张表中的记录,其实是可以同时更新两张表的,如下sql: 

UPDATE product p 

INNER JOIN productPrice pp 

ON p.productId = pp.productId 

SET pp.price = pp.price * 0.8, 

p.dateUpdate = CURDATE() 

WHERE p.dateCreated < '2004-01-01' 

两张表做关联,更新了ProductPrice表的price字段和Product表字段的dateUpdate两个字段。

update table_1 set score = score + 5 where uid in (select uid from table_2 where sid = 10);

其实update也可以用到left join、inner join来进行关联,可能执行效率更高,把上面的sql替换成join的方式如下:

update table_1 t1 inner join table_2 t2 on t1.uid = t2.uid set score = score + 5 where t2.sid = 10;

mysql关联多表进行update更新操作

 代码如下复制代码

UPDATE Track

INNER JOIN MV

ON Track.trkid=MV.mvid

SET Track.is_show=MV.is_show

WHERE trkid<6

等同于

UPDATE Track,MV

SET Track.is_show=MV.is_show

WHERE Track.trkid=MV.mvid and trkid<6

update student s, city c

   set s.city_name = c.name

 where s.city_code = c.code;

也可以试下面的相关子查询:

update student s set city_name = (select name from city where code = s.city_code);

============================================================

e.g.

update t_xd_after_loan_core a, t_xd_loan_extend e 

set a.bid_limit = e.bid_limit,a.bid_borrow_period_unit=e.bid_borrow_period_unit 

where a.bid =e.bid and a.create_date < '2017-06-22 22:00:00' and a.play_money_type in (1,3,10); 

update t_xd_after_loan_core a 

set a.bid_limit=1,a.bid_borrow_period_unit=2 

where a.create_date < '2017-06-22 22:00:00' and a.play_money_type in (5,6) and a.refund_way=5; 

update t_xd_after_loan_core a, t_xd_loan_extend e 

set a.bid_limit = e.bid_limit,a.bid_borrow_period_unit=e.bid_borrow_period_unit 

where a.bid =e.bid and a.create_date < '2017-06-22 22:00:00' and a.play_money_type in (5,6) and a.refund_way=4; 

猜你喜欢

转载自gaozzsoft.iteye.com/blog/2381178