Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MySQL with BIT_AND operator

Im have a database which saves user preferences in binary.

Chips = 1;
Pizza = 2;
Chinese = 4;

For example, if a user likes chips, then their preference will be 1. If they like pizza, their preference will be 2. If the like both, their preference will be 3. If they like chinese and chips, but not pizza, then their preference will be 5.

I need to create a mysql query where I can select all users who DO NOT like Pizza. I have attempted to solve this problem, but Im finding a lack of docs for using bit and in a where clause:

Logically, this makes sense to me, but this is not right:

SELECT * FROM `User` WHERE BIT_AND(preferences,2) != 2;
like image 430
RonnyKnoxville Avatar asked Feb 13 '26 05:02

RonnyKnoxville


1 Answers

SELECT * FROM `User` 
WHERE preferences & 2 = 0

Source

SQLFiddle demo

like image 88
juergen d Avatar answered Feb 15 '26 19:02

juergen d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!