bitscn.com
mysql跨表更新
假定我们有两张表,一张表为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两个字段。
bitscn.com