简体   繁体   中英

mysql update multiple column one row single statement vs multiple statements

I am trying to update 3 column values in a row in mysql only if any of the 3 values is different.

Say I have a table of

x,y,z,id columns

I have currently,

Method 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'))

I don't know much about the theoretical benchmarking/architecture of mysql, and I was wondering if the statements

Method 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')); 

is better or superior.

I realize that Method B will only do one write and 3 reads if only one column has changed, vs 3 writes and 3 reads for the Method A. I just don't know if it is more time intensive because method B requires looking up the index row 3 times.

Thanks in advance!

Based on what I've read in the comments, I agree with octern that you should simply run an update. It will use significantly less resources and based on your table engine, it will free up your table/ row lock for less time, making your table perform a lot better.

However, if you insist on doing a check before doing a write, do so through PHP. Simply do a select statement, compare the code in PHP and then update the appropriate table(s). For example:

$res = mysql_query("SELECT * FROM table1 WHERE PK_ID = '0'");
$arr = mysq_fetch_assoc($res);
$update = false;
if ($arr["field_1"] != $_POST["field_1"])
{
    $update = true;
}

if ($arr["field_2"] != $_POST["field_2"])
{
    $update = true;
}

if ($update)
{
    mysql_query(sprintf("UPDATE table1 SET field_1 = '%s', field_2 = '%s'", $_POST["field_1"], $_POST["field_2"]));
}
if (

Method B will of course be more costly, because you do 3 different selects vs Method A's single select / update on condition.

Its pretty much a comparison of 1 statement to 3 statements. 1 will be faster as they are both update statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM