将 BINARY 数据类型与 MySQL 中的二进制模式匹配

Match BINARY datatype against binary pattern in MySQL

假设 BINARY 列具有以下值:

1001001
0101001
1110110
1101101

匹配二进制模式的最有效方法是什么?
想到任何非正则表达式方法吗?

*1*1**1

上面示例中的匹配值:

0101001
1101101

在固定长度值的情况下,您可以使用 substring()

mysql> select substring('0101001',2,1) as pos1 ,substring('0101001',4,1) pos2,substring('0101001',7,1) pos3;
+------+------+------+
| pos1 | pos2 | pos3 |
+------+------+------+
| 1    | 1    | 1    |
+------+------+------+
1 row in set (0.00 sec)

所以你可以在select语句中使用上面的作为

select * from table_name
where
substring(col_val,2,1) = 1
and substring(col_val,4,1) = 1
and substring(col_val,7,1) = 1

把它当作一个二进制数,然后用布尔运算。

mysql> SELECT CONV('0101001', 2, 10) & b'0101001' = b'0101001';
+--------------------------------------------------+
| CONV('0101001', 2, 10) & b'0101001' = b'0101001' |
+--------------------------------------------------+
|                                                1 | -- means TRUE
+--------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CONV('0000000', 2, 10) & b'0101001' = b'0101001';
+--------------------------------------------------+
| CONV('0000000', 2, 10) & b'0101001' = b'0101001' |
+--------------------------------------------------+
|                                                0 | -- means FALSE
+--------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CONV('0000111', 2, 10) & b'0101001' = b'0101001';
+--------------------------------------------------+
| CONV('0000111', 2, 10) & b'0101001' = b'0101001' |
+--------------------------------------------------+
|                                                0 |
+--------------------------------------------------+