Storing a binary string in MySQL

I developed a small binary flag system for our central administration. This allows us to set elements with several parameters assigned to them, without the need to store a table with several fields.

As soon as the parameters are converted to binary with bitwise operators, we get an option such as 10000 or 10010, which is all right. Performing this method allows us to add additional parameters, but without re-writing what value is 10010 and (1 <4), and I know that we have included something.

However, the problem is storing this data in our MySQL table. I tried several types of fields, but none of them allows me to execute a request, for example,

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

Suggestions?

+6
source share
2 answers

To check if a bit is set, your request should be:

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

And check if this is installed:

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

Update : here, how to set a separate bit:

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

To clear a single bit:

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

You can also install them all at once using a binary string:

 UPDATE table SET options = b'00010010' 
+3
source
+1
source

Source: https://habr.com/ru/post/886776/


All Articles