Is there a way in MySQL to reverse a boolean field with one query?

后端 未结 4 1667
故里飘歌
故里飘歌 2021-01-01 11:06

I have a column in my table titled \'authorised\'. Its default is 0. It needs to be changed to 1 when the user is authorised, but it must be able to be reset to 0. I know I

相关标签:
4条回答
  • 2021-01-01 11:27

    Its also possible to use XOR if your 'boolean' field is implemented as a TINYINT:

    UPDATE users SET authorised = authorised XOR 1 WHERE id = 2;
    

    This will set 'authorised' to 0 if currently 1, and to 1 if currently 0. It will also zeroise all non-zero values, so is an ideal solution if you (like me) use several positive values to reflect a variety of 'on' levels, but always need to revert to 0 when 'off'.

    0 讨论(0)
  • 2021-01-01 11:34

    There are multiple ways to do this, here's a simple one:

    UPDATE users SET authorised = ABS(authorised - 1) WHERE id = 2;
    
    0 讨论(0)
  • 2021-01-01 11:39
    UPDATE users SET `authorised` = IF (`authorised`, 0, 1)
    
    0 讨论(0)
  • 2021-01-01 11:46
    UPDATE `users` SET `authorised` = NOT `authorised` WHERE id = 2
    

    This query will also work to negate the field, and is more inline with boolean syntax.

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