在所有成功或全部失败的情况下运行多个查询

时间:2016-03-23 05:22:10

标签: mysql sql-update sql-insert atomic

我需要将2行更新到2个不同的表中,然后在另一个不同的表中插入一个新行,必须这样做,否则它们都会成功或失败。 (我认为这个词是原子的?)。我做了一些搜索,但似乎只能找到与对一个表进行多次插入或更新相关的问题。

以下是我需要运行的3个查询:

UPDATE submission SET status='a' WHERE idgreg = 119 AND status='p' AND userid = 126;

UPDATE greg SET iscomplete=1 WHERE idgreg = 119;

INSERT INTO completion (idperson, idgreg, datecompleted, idsubmission, mediaid, description, 
privatestatus, contenttype, totalamount)  
SELECT s.idperson, s.idgreg, s.datesubmitted, s.idsubmission, COALESCE(s.youtubeid, s.contentid) AS mediaidid, g.description, g.privatestatus, 
g.contenttype, COALESCE(SUM(amount),0) AS totalamount 
FROM submission s 
INNER JOIN greg g on s.idgreg = g.idgreg 
INNER JOIN contribution c on s.idgreg = c.idgreg 
WHERE s.idsubmission = 36 AND c.ispaid = 1;

1 个答案:

答案 0 :(得分:1)

您应该将查询包装在MySQL 事务中,以确保它们以原子方式执行。但首先,声明错误处理程序,它将ROLLBACK发生错误时所有更改:

CREATE PROCEDURE runYourQueries()

BEGIN

DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
DECLARE EXIT HANDLER FOR SQLWARNING ROLLBACK;

START TRANSACTION;

UPDATE submission SET status='a' WHERE idgreg = 119 AND status='p' AND userid = 126;

UPDATE greg SET iscomplete=1 WHERE idgreg = 119;

INSERT INTO completion (idperson, idgreg, datecompleted, idsubmission, mediaid, description,
    privatestatus, contenttype, totalamount)  
SELECT s.idperson, s.idgreg, s.datesubmitted, s.idsubmission,
    COALESCE(s.youtubeid, s.contentid) AS mediaidid, g.description, g.privatestatus,
    g.contenttype, COALESCE(SUM(amount),0) AS totalamount 
FROM submission s 
INNER JOIN greg g on s.idgreg = g.idgreg 
INNER JOIN contribution c on s.idgreg = c.idgreg 
WHERE s.idsubmission = 36 AND c.ispaid = 1;

COMMIT;

END