mysql 二进制串,存储在MySQL中的二进制字符串

I've developed a small binary flag system for our admin centre. It allows us to set items to have multiple options assigned to them, without having to store have a table with several fields.

Once the options are converted into binary with bitwise operators, we'd end up with an option like 10000 or 10010 which is all good. Doing it this way allows us to keep adding options, but without having to re-write which value is which, 10010 & (1 << 4) and I know that we have something turned on.

The problem however is storing this data in our MySQL table. I've tried several field types, but none of them are allowing me to perform a query such as,

SELECT * FROM _table_ x WHERE x.options & (1 << 4)

Suggestions?

解决方案

To check if a bit is set your query needs to be:

SELECT * FROM _table_ x WHERE x.options & (1 << 4) != 0

And to check if it's not set:

SELECT * FROM _table_ x WHERE x.options & (1 << 4) = 0

Update: Here's how to set an individual bit:

UPDATE table SET options = options | (1 << 4)

To clear an individual bit:

UPDATE table SET options = options &~ (1 << 4)

You can also set them all at once with a binary string:

UPDATE table SET options = b'00010010'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值