我一次性更新两个表的语法有问题。我的代码目前如下所示:
if ($stmt = $mysqli->prepare('
BEGIN TRANSACTION
UPDATE items_woods
SET items_woods.oak = ´1´
FROM items_woods T1, skills_woodcutting T2
WHERE T1.id = T2.id
and T1.id = ´?´
UPDATE skills_woodcutting
SET skills_woodcutting.exp = ´1´
FROM items_woods T1, skills_woodcutting T2
WHERE T1.id = T2.id
and T1.id = ´?´
COMMIT
')) {
/* Bind parametres */
$stmt->bind_param('i', $id);
/* Insert the parameter values */
$id = 1;
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terrible wrong' . $mysqli->error;
}
我正在运行 MySQL 服务器,但我看不出问题出在哪里,如果有人能提示我正确的语法,我将不胜感激。谢谢。
最佳答案
I have tried following this post:How to update two tables in one statement in SQL Server 2005?
对于您的情况,上述帖子不是一个好的信息来源,因为它是针对 SQL Server 而不是 MySQL。
SQL Server 和 MySQL 对于 UPDATE
有不同的语法:
- SQL Server 不允许同时更新多个表,而 MySQL 允许。因此您不需要两次更新。
- 在 MySQL 中,
SET
子句位于所有表引用之后,而在 SQL Server 中,则在 SQL Server 中位于FROM
子句之前 - 在 MySQL 中,
UPDATE
中没有FROM
子句
也就是说,在 MySQL 中,您可以使用 a proper multi-table syntax 在一个 UPDATE 语句中完成此操作。
UPDATE items_woods t1 JOIN skills_woodcutting t2
ON t1.id = t2.id
SET t1.oak = 1,
t2.exp = 1
WHERE t1.id = ?;
这里是SQLFiddle 演示
<小时/> 你的 php 代码归结为$id = 1;
$sql = 'UPDATE items_woods t1 JOIN skills_woodcutting t2
ON t1.id = t2.id
SET t1.oak = 1,
t2.exp = 1
WHERE t1.id = ?';
if ($stmt = $db->prepare($sql)) {
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
} else {
die('Error: ' . $db->error); //TODO:better error handling
}
<小时/>
现在,除了 SQL Server 和 MySQL 之间的 UPDATE 语法存在差异之外,如果由于某种原因,您需要发出多个更新语句,那么您的代码仍然会存在其他问题:
- 您无法使用
prepare()
和execute()
一次性准备和执行多个 SQL 语句;您可以一一准备并执行它们,也可以使用 mysqli_multi_query() - 如果您使用
mysqli_multi_query()
,则必须用分号;
终止每个 SQL 语句。
关于mysql - SQL更新两个表事务语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817808/