4

这是我的 sql 查询,flag(00000)每个位都有不同的规格,例如change 4th bit position to 1 when user is inactive. 这里的标志是 varchar 数据类型(字符串)。

$sql="select flag from user where id =1"

我有

flag=10001 #it may be flag="00001" or flag="00101"

我想将此标志的第二位更新为 1。

$sql="update user set flag='-1---' where id=1" #it may be flag='11001' or flag='01001' or flag='01110'

实际上,我想将此标志的第二位更新为 1,但没有像 flag='11001' 那样更新它。我想做这样的事情。

$sql="update user set flag='--change(flag,2bit,to1)--' where id =1" #this is wrong

我可以为它做些什么,只使用一个 sql 查询?有可能吗?

4

3 回答 3

6
update user
set flag = lpad(conv((conv(flag, 2, 10) | 1 << 3), 10, 2), 5, '0')
where id = 1
  • conv(flag, 2, 10)将标志字符串从二进制转换为十进制。
  • 1 << 3向左移动 1 位 3 个二进制位
  • | performs a binary OR of this, to set that bit. This arithmetic operation will automatically coerce the decimal string to a number; you can use an explicit CAST if you prefer.
  • conv(..., 10, 2) will convert the decimal string back to a binary string
  • lpad(..., 5, '0') adds leading zeroes to make the string 5 characters long

FIDDLE DEMO

To set the bit to 0, you use:

set flag = lpad(conv((conv(flag, 2, 10) & ~(1 << 3)), 10, 2), 5, '0')
于 2013-07-30T07:06:37.203 回答
3

你想使用按位或运算符|

update user set flag = flag | (1 << 1) where id =1

如果标志是 101 标志现在将是 111

如果标志是 000 标志现在将是 010

1 << 1 将 1 向上移动一位 - 使其为 10(二进制 2)

编辑 - 未经测试但使用

update user set flag = cast(cast(flag AS SIGNED) | (1 << 1) AS CHAR) where id =1 
于 2013-07-30T06:59:19.173 回答
0

If you are going to use a VARCHAR, you are better off using string manipulation functions: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

UPDATE user
SET flag = CONCAT(LEFT(flag, 1), '1', RIGHT(flag, 3))
WHERE id = 1

However, you probably want to convert this field to an INT so that you can use the bit functions: http://dev.mysql.com/doc/refman/5.0/en/bit-functions.html

于 2013-07-30T08:15:25.793 回答