在MySQL中同时更新多表

时间:2012-04-05 10:32:12

标签: mysql

我有下面的查询,我需要它在一个更新查询中。由于我是初学者,我使用连接并编写单行查询,但我得到错误

  

超过锁定等待超时;尝试重新启动交易

以下是每个个人更新查询...

update a set id=id-1 where id>'3' and reg='34554';
update b set id=id-1 where id>'3' and reg='34554';
update c set id=id-1 where id>'3' and reg='34554';
update d set id=id-1 where id>'3' and reg='34554';
update e set id=id-1 where id>'3' and reg='34554';

下面是我尝试过的,并且如上所述得到了错误......

update a
LEFT JOIN b ON b.id=a.id and b.tan=a.tan
LEFT JOIN c ON c.id=b.id and c.tan=b.tan
LEFT JOIN d ON d.id=c.id and d.tan=c.tan
LEFT JOIN e ON e.id=d.id and e.tan=d.tan
SET a.id=b.id=c.id=d.id=e.id=a.id-1
where a.id>'3' and a.tan='34554';

2 个答案:

答案 0 :(得分:1)

您可以在存储过程中存储多个sql,然后从java调用该过程.Id& reg可以传递参数。

有关存储过程的信息http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html

你必须在Mysql命令行中执行此操作...

Delimiter |

Create procedure (in id_val int, in reg_val int)

Begin

update a set id=id-1 where id>id_val and reg=reg_val;

update b set id=id-1 where id>id_val and reg=reg_val;

update c set id=id-1 where id>id_val and reg=reg_val;

update d set id=id-1 where id>id_val and reg=reg_val;

update e set id=id-1 where id>id_val and reg=reg_val;

End |

delimiter ;

我在以下链接中使用PHP ... info http://php.net/manual/en/pdo.prepared-statements.php

希望java ...这个链接可能有用 http://www.easywayserver.com/jdbc/JDBC-prepared-statement.htm

答案 1 :(得分:0)

您必须使用交易

SET autocommit=0;
LOCK TABLES a WRITE, b WRITE, c WRITE, d WRITE, e WRITE

update a set id=id-1 where id>'3' and reg='34554';
update b set id=id-1 where id>'3' and reg='34554';
update c set id=id-1 where id>'3' and reg='34554';
update d set id=id-1 where id>'3' and reg='34554';
update e set id=id-1 where id>'3' and reg='34554';

COMMIT;
UNLOCK TABLES;

您可以阅读有关将锁定表与事务here

组合的信息

我不知道,如何使用join创建此类查询。