MySQL:切换 int 字段值的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/603835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:52:19  来源:igfitidea点击:

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

mysql

提问by fmsf

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)

你怎么能做到这一点(伪sql中的例子)

UPDATE some_table SET an_int_value = (an_int_value==1 ? 0 : 1);

It must be an int value due to some other functionality, but how do you do it in a simple way?

由于某些其他功能,它必须是一个 int 值,但是您如何以简单的方式做到这一点?

回答by FDisk

UPDATE table SET field = 1 - field

回答by Glavi?

UPDATE some_table SET an_int_value = IF(an_int_value=1, 0, 1)

回答by Eric Petroelje

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

在这种情况下,您可以使用 XOR 类型的操作:

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.

这是假设 an_int_value 将始终为 1 或 0。

回答by Jayapal Chandran

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... .

如果这不是一个可行的解决方案,任何机构都可以提出建议。关于执行速度或任何其他...说什么...事实...概念...。

回答by Chad Birch

Another option:

另外一个选项:

UPDATE some_table SET an_int_value = ABS(an_int_value - 1);

回答by George-Paul B.

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)

如果您使用 TINYINT(0 和 1),则执行简单的 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 */

选择 0 ^ 1; /* 返回 1 */

SELECT 1 ^ 1; /* returns 0 */

选择 1 ^ 1; /* 返回 0 */

回答by Dave

For ENUM(0,1) fields you can use...

对于 ENUM(0,1) 字段,您可以使用...

UPDATE table SET int_value=BINARY(int_value=1)

更新表 SET int_value=BINARY(int_value=1)

回答by geethika

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

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