Bit operations in MySQL (Work with flags)


#Set flag 0x2: UPDATE `table` SET `flag`=`flag` | (0x2); #Set just a few bits (0x1 и 0x2): UPDATE `table` SET `flag`=`flag` | (0x1|0x2); #To remove the flag 0x2: UPDATE `table` SET `flag`=`flag` &~ (0x2); #Delete several bits (0x1 и 0x2): UPDATE `table` SET `flag`=`flag` &~ (0x1|0x2); #Check the flag 0x2: SELECT * FORM `table` WHERE (`flag` & 0x2) != 0 #The same for checking the presence of at least one bit of the mask 0x3. That is, if the bits set 0x1 or 0x2. SELECT * FORM `table` WHERE (`flag` & 0x3) != 0 #Check for all bits of the mask 0x3. That is, if the bits set 0x1 и 0x2 at the same time. SELECT * FORM `table` WHERE (`flag` & 0x3) = 0x3
Crib for bit operations:
0x1|0x2 = 0x3 // adding
0x3&0x2 = 0x2 
0x1&0x2 = 0x0 
0x3&~0x2 = 0x1