简体   繁体   中英

MySQL bitwise in WHERE statement returning odd results

I have a BLOB field in a MySQL database that contains a seven bit binary field - in essence, one bit for each day of the week, starting on a Sunday with the right hand bit.

I have two records, on one the binary field (called Flags) is set to 0101000 while the other is set to 0000010. I use Querious software on a Mac for database work, and that shows that the field does contain binary data and confirms the above entries.

However, when I issue a SELECT statement, that includes Flags & 8 = 8 in the WHERE statement, both records are returned, yet I believe only the first should be.

The PHP code using bindec($data->flags) & 8 correctly only marks the first record as having the 4th bit (ie value 8) set.

Can anyone advise what I'm doing wrong with the MySQL statement - i've been looking at this for over 36 hours now, and just cant see it.

Seems to work in fine here here (on v5.7.13)

mysql> create table z (x bit(7));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into z (x) values (0b0101000), (0b000010);
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select cast(x & 8 as unsigned) from z;
+-------------------------+
| cast(x & 8 as unsigned) |
+-------------------------+
|                       8 |
|                       0 |
+-------------------------+
2 rows in set (0.00 sec)

mysql> select x, cast(x as unsigned) from z where x & 8;
+------+---------------------+
| x    | cast(x as unsigned) |
+------+---------------------+
| (    |                  40 |
+------+---------------------+
1 row in set (0.00 sec)

You should show your ACTUAL query.

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