简体   繁体   中英

Combine two UPDATE queries on the same field but with different values

I currently have two queries using PDO / MySQL:

$sql = "UPDATE permissions SET valid = 'N' WHERE perm_desc = :perm_desc";
$sth = $this->db->prepare($sql);
$sth->bindParam(':perm_desc', $perm_desc);

$sql2 = "UPDATE role_perm SET valid = 'N' WHERE perm_id = :perm_id";
$sth2 = $this->db->prepare($sql2);
$sth2->bindParam(':perm_id', $perm_id);

I'm wondering if it would make more sense to combine these, something along the lines of:

$sql = "UPDATE permissions, role_perm
        SET permissions.valid = 'N', role_perm.valid = 'N'
        WHERE permissions.perm_desc = :perm_desc AND role_perm.perm_id = :perm_id";

I have trouble wrapping my head around JOINs and some people say they are faster while others say they are slower. What is the best solution?

With your current approach of two different updates, you must handle the case of the failure of the second update and rollback manually the first update. If you rely in an open transaction to handle the failure for you, then you are leaving a transaction in the database open longer than needed.

But after all, it depends on your requirements. If you need to perform both updates or neither (rollback in case of the second one failing) then I'd rather go with the one sentence approach. In this way you can benefit from transactions.

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