英文:
Mysql Rollback Transaction if Insert Into Select fails
问题
If the id in table1 does not exist, and the nested SELECT is null, you can make the transaction fail by adding a condition to check if the SELECT statement returns any rows. If it doesn't return any rows, the transaction will not insert anything into relation_table1_table2, effectively failing.
Here's the modified code:
INSERT INTO table2 ..... ;
SET @table2_insert_id = LAST_INSERT_ID();
INSERT INTO relation_table1_table2 (table1_id, table2_id)
SELECT id, @table2_insert_id FROM table2
WHERE table1.column1 = 'ABC'
AND EXISTS (SELECT 1 FROM table1 WHERE column1 = 'ABC');
By using the EXISTS
condition, the second INSERT will only occur if there is a matching row in table1 where column1
is 'ABC'. If no such row exists, the transaction will fail to insert into relation_table1_table2.
英文:
I have 3 tables - table1, table2, relation_table1_table2. To insert a row into table2 I am running a transaction like this:
INSERT INTO table2 ..... ;
SET @table2_insert_id = LAST_INSERT_ID();\
INSERT INTO relation_table1_table2 (table1_id, table2_id)
SELECT id, @table2_insert_id FROM table2
WHERE table1.column1 = 'ABC';
What if the id in table1 does not exist and the nested Select is null. How to make this transaction fail in that scenario? Cant do stored procedure.
答案1
得分: 1
你可以在`INSERT`后调用`ROW_COUNT()`来获取插入的行数。如果为零,则触发错误。
IF ROW_COUNT() == 0
THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '未找到要插入的内容';
END IF;
如果不能使用SQL条件语句,请在JavaScript中执行条件检查。
db.query(INSERT INTO relation_table1_table2 (table1_id, table2_id)
, function(err, res) {
SELECT id, @table2_insert_id FROM table2
WHERE table1.columnX = 'ABC'
if (err) {
throw "查询失败";
}
if (res.affectedRows == 0) {
db.rollback();
throw "未插入任何内容";
}
});
<details>
<summary>英文:</summary>
You can call `ROW_COUNT()` after the `INSERT` to get the number of rows inserted. If it's zero, raise an error.
IF ROW_COUNT() == 0
THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Nothing found to insert';
END IF;
If you can't use SQL conditional statements, do the condition in JavaScript.
db.query(INSERT INTO relation_table1_table2 (table1_id, table2_id)
, function(err, res) {
SELECT id, @table2_insert_id FROM table2
WHERE table1.columnX = 'ABC'
if (err) {
throw "Query failed";
}
if (res.affectedRows == 0) {
db.rollback();
throw "Nothing inserted";
}
});
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论