赞
踩
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` bigint(20) NOT NULL COMMENT '主键id',
`ancestors` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '组织层级',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `test` VALUES (1, '0,1,2,3');
INSERT INTO `test` VALUES (2, '0,2,4,5,6');
INSERT INTO `test` VALUES (3, '11,33,6,22');
INSERT INTO `test` VALUES (4, '0,1,2,3,4,5,6,7,8,9,11');
INSERT INTO `test` VALUES (5, '2,3,4,5,6,7');
INSERT INTO `test` VALUES (6, '1,22,66,16,36');
INSERT INTO `test` VALUES (7, '46,12,32,18');
INSERT INTO `test` VALUES (8, '77,76,75,74');
SET FOREIGN_KEY_CHECKS = 1;
数据库有一个字段ancestors存储着部门父级id,每,用逗号分隔符隔开。比如:ancestors:“0,1,2,3,4,5,6,7,8,11,12,9,10,13"”,我需要查询ancestors字段中包含“2”的信息
-- 表中数据示例
select * from `test`
结果:
select * from `test` where ancestors like '%8';
结果:
使用 FIND_IN_SET 函数能够准确查出 ancestors字段中含有 2 这项有哪些
select id,ancestors from `test` where find_in_set('2',ancestors) GROUP BY id;
结果:
我们在SQL中用WHERE子句搜索匹配的条件时,常用到LIKE关键字,今天来简单介绍另一种更加强大的关键字: REGEXP, 正则匹配。
select id,ancestors from `test` where ancestors REGEXP '.*2';
结果:
这个函数,会把你查询出含有查找 “ 2 ” 的数据
select id,ancestors from `test` where LOCATE ('2',ancestors);
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。