MySQL 按位运算符的状态交换
我正在寻找一种解决方案/最佳实践来交换状态标志的值。
mysql 中的状态 INT(3) 有几个值,我希望能够交换 LIVE 和 NOT_LIVE 值,而不中断其中的其他按位值。
如果它是一个标志字段,如 0 或 1,这很容易:
'status' NOT 'status'
我想知道是否有一种方法可以基于两个值 (x, y) 进行交换 - 无需太多代码逻辑,如代码多于。当然,我可能是在做梦,只需恢复到 SELECT 查询、if 语句和 UPDATE...
有什么想法吗?
I am looking for a solution/best practice to do a swap of values for a status flag.
The status INT(3) in mysql has a few values, and I'd like to be able to swap the LIVE and NOT_LIVE values around, without interrupting what other bitwise values are in there.
If it was a flag field, as in 0 or 1, it is easy:
'status' NOT 'status'
I was wondering if there was a way I could do a swap based on two values (x, y) - without too much code-logic, like the code above. Of course I may be dreaming, and just have to revert to a SELECT query, and if statement and an UPDATE...
any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所以你的值是 1 和 2,但你想要位式翻转?这是行不通的,因为 1 和 2 设置了不同的位!
试试这个:
so your values are 1 and 2, but you want bit-style flipping? that won't work because 1 and 2 have different bits set!
try this:
“交换[ping] LIVE 和 NOT_LIVE 值”到底是什么意思?如果
LIVE
是一个已设置/未设置的位,那么您正在寻找的是按位 NAND。例如,如果它的值为 8 并且您想要取消设置它,它将取消设置值为 8 的位。如果
LIVE
和NOT_LIVE
为两个不同的位,那么您需要设置一个(OR)并取消设置另一个(NAND)。在这里,我将在设置LIVE
(8) 时删除NOT_LIVE
(4)如果
status
可以只有两个值那么您需要的是将这两个值相加,然后减去status
。例如,如果两个值是 1 和 2,当然您可以编写
注意,如果
status
采用任何其他值,这将失败。如果是两者之一,您可以通过仅更改status
来避免这种情况。在这种情况下,如果
status
既不是LIVE
也不是NOT_LIVE
,则不会更改。What do you mean exactly by "swap[ping] the
LIVE
andNOT_LIVE
values" ? IfLIVE
is a bit that is set/unset then what you are looking for is a bitwise NAND. For instance, if its value is 8 and you want to unset itIt will unset the bit whose value is 8. If
LIVE
andNOT_LIVE
are two different bits then you'll need to set one (OR) and unset the other (NAND). Here I'll removeNOT_LIVE
(4) while settingLIVE
(8)If
status
can only have two values then what you need is add those two values then substractstatus
. For instance, if the two values are 1 and 2which of course you can write
Note that this will fail if
status
takes any other value. You can avoid that by only changingstatus
if it's one of the two.In this case, if
status
is neitherLIVE
orNOT_LIVE
, it won't be changed.您需要此处的 case 语句:
或者,您可以使用 if 语句,如果你愿意的话:
You need the case statement here:
Alternately, you can use the if statement, if you like: