简体   繁体   中英

Mysql: How do I select a if a bit on a specific place is 1?

I have a mysql column with an integer containing info about the by a user selected options.

Now, for example, the number 42 = 2 + 8 + 32 = 2^ 1 + 2^ 3 + 2^ 5 , so a user with options = 42 has option 1,3 and 5 selected.

How do I select all the users with (at least) option 5 selected? What would be a correct working sql query?

SELECT * FROM `users` WHERE ???(`options`) = ???(5);

Thanks in advance!

IF options is an integer type, you can select the rows with at least bit 5 set in their options like this:

SELECT * FROM `users` WHERE `options` >= POW(2, 5)

To select only columns with bit 5 set in their options, do

SELECT * FROM `users` WHERE (`options` & POW(2, 5))

Try bitwise operations:

http://dev.mysql.com/doc/refman/5.0/en/bit-functions.html

in your code (MySql) the condition could be

SELECT * 
  FROM `users` 
 WHERE (`options` & (1 << 5)) <> 0 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM