Mysql updates multi table update sql statement summaries across tables
- 2020-05-14 05:12:37
- OfStack
Suppose we have two tables, one for the Product table to store the product information, in which there is the product price list Price; The other table is the ProductPrice table, and we will update the price field Price in the ProductPrice table to 80% of the price field in the Price table.
There are several ways to do this in Mysql, one is update table1 t1, table2 ts... The way:
Another way is to use inner join and then update it:
In addition, we can also use left outer join to do long table update. For example, if there is no product price record in ProductPrice table, set isDeleted field in Product table to 1. sql statement is as follows:
In addition, the above examples are all related between two tables, but it is possible to update the records in only one table at the same time, as shown in sql:
The two tables are related, and the price field of ProductPrice table and dateUpdate field of Product table are updated.
There are several ways to do this in Mysql, one is update table1 t1, table2 ts... The way:
UPDATE product p, productPrice pp
SET pp.price = pp.price * 0.8
WHERE p.productId = pp.productId
AND p.dateCreated < '2004-01-01'
Another way is to use inner join and then update it:
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'
In addition, we can also use left outer join to do long table update. For example, if there is no product price record in ProductPrice table, set isDeleted field in Product table to 1. sql statement is as follows:
UPDATE product p
LEFT JOIN productPrice pp
ON p.productId = pp.productId
SET p.deleted = 1
WHERE pp.productId IS null
In addition, the above examples are all related between two tables, but it is possible to update the records in only one table at the same time, as shown in 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'
The two tables are related, and the price field of ProductPrice table and dateUpdate field of Product table are updated.