当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql跨表更新 多表update sql语句总结

Mysql跨表更新 多表update sql语句总结

2017年12月12日  | 移动技术网IT编程  | 我要评论
假定我们有两张表,一张表为product表存放产品信息,其中有产品价格列price;另外一张表是productprice表,我们要将productprice表中的价格字段price更新为price表中价格字段的80%。
在mysql中我们有几种手段可以做到这一点,一种是update table1 t1, table2 ts ...的方式:
复制代码 代码如下:

update product p, productprice pp
set pp.price = pp.price * 0.8
where p.productid = pp.productid
and p.datecreated < '2004-01-01'

另外一种方法是使用inner join然后更新:
复制代码 代码如下:

update product p
inner join productprice pp
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两个字段。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网