MySQL like 中 下划线占位符的测试案例。在MySQL的like语句中,_不是代表普通的下划线,而是代表一个字符,LIKE 'chaptertype %1_%' 相当于匹配 chaptertype 字段包含1X(X代表任意字符)字符串,如果要匹配下划线,需要加转义符chaptertype LIKE '%1\_%'
测试案例:
创建表结构:
CREATE TABLE `d_like` ( `id` int(11) NOT NULL COMMENT '主键id', `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '姓名', `code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '编码', PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;插入一批测试数据:
INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (1, 'A01', '1110000');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (2, 'A02', '1110010');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (3, 'A03', '0011111');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (4, 'A04', '0010111');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (5, 'A05', '0010100');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (6, 'A06', '1110000');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (7, 'A07', '10101_1');INSERT INTO `t_like`(`id`, `name`, `code`) VALUES (8, 'A08', '101__11');测试mysql like 中 下划线占位符模糊查询第四位和第五位为01的数据。并且位数为7位。(因为算上下划线占位符一共是7位):
select * from t_like where `code` like '___01__';数据查询结果如下:
如果想查询含有下划线的数据,那么需要加转移符:
select * from t_like where `code` like '%\_%';数据查询结果如下: