场景: 测试人员需要查询特定字段里里面的特定字符串,但是正则不会写,看到了SUBSTRING来截取特定字符串,感觉不错。


1:数据如下
CREATE TABLE erp_orgs (
id int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
path varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '-' COMMENT '层级路径',
PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5044 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
2:插入数据
INSERT INTO hanye.erp_orgs(id, path) VALUES (1, '1-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (2, '1-2-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (3, '1-2-3-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (4, '1-2-4-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (5, '1-2-5-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (6, '1-2-4-6-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (7, '1-2-3-7-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (8, '1-2-3-8-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (9, '1-2-3-7-9-');
INSERT INTO hanye.erp_orgs(id, path) VALUES (10, '1-2-3-7-10-');

3:开始查询自己需要的字段
A:取path的字段的后面三位
select SUBSTRING(path, -3) from erp_orgs;
-2-
-3-
-4-
-5-
-6-
-7-
-8-
-9-
10- (未知结果 后续查找)
(重点: 如果字段长度不足 展示结果为空)
B:从左开始第3位取(包括第三位)
select SUBSTRING(path, 3) from erp_orgs;
C:取左边的3位
select SUBSTRING(path, 1,3) from erp_orgs;
这种只能针对固定长度,比说url共8个字符,可以下面这种写法
select SUBSTRING(path,length(url)-5) from erp_orgs;
4:正式查询 例如查询后面的数字为id的 一般后面都带有 - 字符
SELECT * from erp_orgs WHERE SUBSTRING(path,-2) = id;