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 1
另一種形式
查詢開啟歸檔的
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 1
異或(^)運算
異或運算通俗地講就是一句話
同為假,異為真
所以它是這樣的算法:
0&0=0,0&1=1,1&0=1,1&1=0
