MySQL 更新多列一行单语句与多语句


mysql update multiple column one row single statement vs multiple statements

当 3 个值中的任何一个不同时,我才尝试在 mysql 中更新一行中的 3 列值。

假设我有一桌

x,y,z,id 列

我目前有,

方法 A

update foo set x = 'x_value', y = 'y_value', z = 'z_value' where id = 'unique_id'
and ((x <> 'x_value') or (y <> 'y_value') or (z <> 'z_value'))

我对mysql的理论基准测试/架构了解不多,我想知道这些陈述是否

方法 B

update foo set x ='x_value' where id = 'unique_id' and ((x <> 'x_value')); 
update foo set y ='y_value' where id = 'unique_id' and ((y <> 'y_value')); 
update foo set z ='z_value' where id = 'unique_id' and ((z <> 'z_value')); 

是更好或更优越的。

我意识到如果只有一列发生了变化,方法 B 只会执行一次写入和 3 次读取,而方法 A 则进行 3 次写入和 3 次读取。我只是不知道它是否更耗时,因为方法 B 需要查找索引行 3 次。

提前感谢!

根据我在评论中读到的内容,我同意 octern 的观点,您应该简单地运行更新。它将使用更少的资源,并且基于您的表引擎,它将释放您的表/行锁定以缩短时间,使您的表性能更好。

但是,如果您坚持在进行写入之前进行检查,请通过 PHP 进行。只需执行一个 select 语句,比较 PHP 中的代码,然后更新相应的表。例如:

$res = mysql_query("从表 1 中选择 *,其中 PK_ID = '0'");$arr = mysq_fetch_assoc($res);$update = 假;if ($arr["field_1"] != $_POST["field_1"]){    $update = 真;}if ($arr["field_2"] != $_POST["field_2"]){    $update = 真;}如果 ($update){    mysql_query(sprintf("UPDATE table1 SET field_1 = '%s', field_2 = '%s'", $_POST["field_1"], $_POST["field_2"]));}如果 (
方法

B 当然会更昂贵,因为您执行 3 个不同的选择与方法 A 的单选择/更新条件相比。

它几乎是 1 个语句与 3 个语句的比较。 1 会更快,因为它们都是更新语句。