简体   繁体   English

使用MySQL批量更新多个表

[英]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, 要在单个查询中更新多个条目,我可以使用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. 假设id是您的PK,它将仅返回一个条目。

Your WHERE clause looks very similar to what you'd use on a JOIN. 您的WHERE子句看起来非常类似于在JOIN上使用的子句。 Maybe you should try JOIN your tables and then update them. 也许您应该尝试加入您的表,然后更新它们。 Check this out: 看一下这个:

https://stackoverflow.com/a/1293347/4024150 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. 我已将其简化为两个表进行演示,但是基本上您的JOIN会为您提供一个在id字段上连接的大表。 You can then use the WHERE clause to identify the fields you want to update over the entire joined table. 然后,您可以使用WHERE子句来标识要在整个联接表上更新的字段。

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. 该解决方案与JOIN结合将产生期望的结果。

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 注意:您要批量执行的所有查询都应在BEGINCOMMIT内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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