简体   繁体   中英

MySQL: Updating all rows setting a field to 0, but setting one row's field to 1

Is there an efficient way to update a selection of rows' field to 0, but set One of these rows to 1 based on an ID.

Basically, I have multiple objects in a database, and I want to toggle between which one is "inuse", so the query will set one of the rows (by id) to inuse=1 and the others to inuse=0.

Thanks :)

UPDATE `table`
SET `inuse` = (`id` = 23)

Sure

UPDATE table SET inuse=IF(id=ABCD, 1, 0)

would set the inuse field to 1 if id is ABCD and 0 otherwise.

UPDATE  table
SET     inuse = (id = @id)
WHERE   id = @id
        OR inuse

This will update only relevant rows.

UPDATE myTable
SET Field = 0
WHERE FieldID <> [WhateverID]

UPDATE myTable 
SET Field = 1
WHERE FieldId = [WhateverID]

Try

update tbl set inuse = if(test, 1, 0);

or shorter

update tbl set inuse = test;

for example

update tbl set inuse = name = 'foo';

If you are after to set a flag, so no other part of the code uses the same object at the same time, it's better if the calling code sets inuse=1 and resets it when done. Otherwise you will end up one thread to mark an object (row) as inuse, and then if another thread needs another object, it will reset the first one, while still in use.

If this is not the case, and you just want be able to set inuse for one, and reset all others, you can use:

UPDATE myTable
SET InUse = CASE
   WHEN myTable.id = @id THEN 1
   ELSE 0
END

if your database uses transactions, this is the best way to do it:

update myTable set inuse = 0;
update myTable set inuse = 1 where id = ?;

if you are not using transactions, then the other answer using CASE is the best option since it's portable. but it will require more CPU time than the two 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