简体   繁体   中英

Update multiple table in Bulk using MySQL

Is there any way to update multiple table in bulk. I found solution for bulk update using single as well as update multiple table using single query. But then looking for a combined solution.

eg: Currently doing like this.

UPDATE a, b, c 
SET a.address = "$address", b.address = "$address", c.address = "$address" 
WHERE a.id = b.a_id AND a.id = c.a_id AND a.id = 123

UPDATE a, b, c 
SET a.address = "$address", b.address = "$address", c.address = "$address" 
WHERE a.id = b.a_id AND a.id = c.a_id AND a.id = 234

etc

This is my current script that update every address one by one.

To update multiple entries in single query I can use like,

UPDATE a SET address = CASE
    WHEN id = 123 THEN 'address1'
    WHEN id = 234 THEN 'address2'
    END

Is there any way to combine these queries, to update multiple table as well as multiple rows in single query?

Thanks

I'm not sure I follow what you mean by "bulk". I assume you mean update multiple entries in each table. In that case you'd need a condition that returns multiple entries to be updated. Assuming that id is your PK it'll only return one entry.

Your WHERE clause looks very similar to what you'd use on a JOIN. Maybe you should try JOIN your tables and then update them. Check this out:

https://stackoverflow.com/a/1293347/4024150


UPDATE a JOIN b ON a.id = b.id
SET a.address = '$address', b.address = '$address
WHERE (some clause that will return all the entries you want)

I've simplified it to two tables for demonstration but basically your JOIN will present you with one big table joined on the id field. You can then use the WHERE clause to identify the fields you want to update over the entire joined table.

You said above that you found a solution to bulk update a single table. This solution combined with the JOIN should yield the desired results.

You can achieve this using transaction

BEGIN TRANSACTION;

UPDATE Table1
SET Table1.field1 = 'new value1' 
WHERE condition1

UPDATE Table2
SET Table2.field3 = 'new value2'
WHERE condition2

COMMIT;

NOTE : all the queries you want to execute in bulk should be within BEGIN and COMMIT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM