Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing binary string in 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?

like image 655
James Avatar asked Apr 27 '11 08:04

James


People also ask

What is binary string in MySQL?

A binary string is a string of bytes. Every binary string has a character set and collation named binary . A nonbinary string is a string of characters. It has a character set other than binary and a collation that is compatible with the character set.

How do I query binary in MySQL?

The MySQL BINARY function is used for converting a value to a binary string. The BINARY function can also be implemented using CAST function as CAST(value AS BINARY). The BINARY function accepts one parameter which is the value to be converted and returns a binary string.

What is BLOB storage in MySQL?

A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types are TINYBLOB , BLOB , MEDIUMBLOB , and LONGBLOB . These differ only in the maximum length of the values they can hold. The four TEXT types are TINYTEXT , TEXT , MEDIUMTEXT , and LONGTEXT .


2 Answers

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'
like image 192
WhiteFang34 Avatar answered Oct 19 '22 16:10

WhiteFang34


Would the SET field type be of any use here?

like image 21
trickwallett Avatar answered Oct 19 '22 16:10

trickwallett