[MySQL] mysql中bitmap的简单运用

bitmap就是在一个二进制的数据中,每个位表明必定的含义,这样最终只须要存一个整型数据,就能够解释出多个含义.
业务中有一个字段专门用来存储用户对某些功能的开启和关闭,若是是传统的思惟,确定是建一个字段来存0表明关闭,1表明开启,那么若是功能不少或者须要加功能开关,就须要不停的建立字段.
使用bitmap的思路就只须要一个字段就能够了,建一个entuserstatus字段,该字段的二进制表示中,从右到作数,从1开始数.好比第19位表明是否开始归档,那么就直接操做这一位的0和1就能够表示该用户是否开启归档功能.算法


email表的第19位,做为归档开启的位,1是开启 0是关闭;262144表明是第19位为1的十进制数
查询开启的
select email,enterpriseId from email where entuserstatus & 262144=262144;
开启归档
update email set entuserstatus = entuserstatus|262144 where id=670602 limit 1
关闭归档
update email set entuserstatus = entuserstatus^262144 where id=670602 limit 1it

另外一种形式
查询开启归档的
select id,email,enterpriseId,entuserstatus from email where entuserstatus>>18 & 1=1;
开启归档
update email set entuserstatus = entuserstatus|(1<<18)  where id=670602 limit 1
关闭归档
update email set entuserstatus = entuserstatus^(1<<18)  where id=670602 limit 1email

 

异或(^)运算
异或运算通俗地讲就是一句话
同为假,异为真
因此它是这样的算法:
0&0=0,0&1=1,1&0=1,1&1=0date

相关文章
相关标签/搜索