Home > Blockchain >  bit operations in mysql
bit operations in mysql

Time:12-30

I am trying to create a simple filtering of records with bit operations by using this manual: https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html

I have four properties that are defined and based on certain content:

  • Filter 1 (field1) gets the value 1 (binary 1)
  • Filter 2 (field2) gets the value 2 (binary 10)
  • Filter 3 (field3) gets the value 4 (binary 100)
  • Filter 4 (field4) gets the value 8 (binary 1000)

I set the values with an update:

UPDATE table SET filter = 1 where field1 = "a";
UPDATE table SET filter = filter|2 where field2 = "b";
UPDATE table SET filter = filter|4 where field3 = "c";
UPDATE table SET filter = filter|8 where field4 = "d";

Now the column is filled for the different properties. I now have values between 0 (no property applies) and 15 (all properties apply).

How do I manage to use them now? If I want to use e.g. the filters 1,2 and 4, I get with:

select * from table where filter = 1|2|8; 

I get the value "11". But actually, "15" should also match, since all four properties are applied here.

I had no success with this, too:

select * from table where filter & (1|2|8); 

Can someone help me? Or am I completely wrong?

CodePudding user response:

Try WHERE (filter & (1|2|8)) = (1|2|8).

But please be aware that this bitmasking approach can't exploit indexes, so it will scale up poorly to megarow tables.

  • Related