MySQL: Simple way to toggle a value of an int field

前端 未结 9 1614
忘掉有多难
忘掉有多难 2021-01-30 10:19

I know how to do this, but i think I\'ll overcomplicate it with double selects and so on.

How can you do this (example in pseudo-sql)

UPDATE some_table S         


        
相关标签:
9条回答
  • 2021-01-30 10:58
    UPDATE table SET field = 1 - field
    
    0 讨论(0)
  • 2021-01-30 11:00
    UPDATE some_table SET an_int_value = IF(an_int_value=1, 0, 1)
    
    0 讨论(0)
  • If you're using TINYINT (0 and 1) then do a simply XOR (https://dev.mysql.com/doc/refman/8.0/en/logical-operators.html#operator_xor)

    UPDATE
        `some_table`
    SET
        `an_int_value` = `an_int_value` ^ 1
    

    Testing:

    SELECT 0 ^ 1; /* returns 1 */

    SELECT 1 ^ 1; /* returns 0 */

    0 讨论(0)
  • 2021-01-30 11:06

    I can see the answers of all experienced people and i too got updated with their answers.

    what about this... i do this way...

    UPDATE tablename SET fieldname = not fieldname
    

    can any body give suggestions please if this will not be a feasible solution. with respect to execution speed or any other... what to say... fact... concept... .

    0 讨论(0)
  • 2021-01-30 11:07

    For ENUM(0,1) UPDATE some_table SET an_int_value = IF(an_int_value='1', '0', '1');

    0 讨论(0)
  • 2021-01-30 11:10

    In this case, you could use an XOR type operation:

    UPDATE some_table SET an_int_value = an_int_value XOR 1
    

    This is assuming that an_int_value will always be 1 or 0 though.

    0 讨论(0)
提交回复
热议问题