測試示例
1、測試數(shù)據(jù)庫表結構
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;
2、測試數(shù)據(jù)
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;
需求描述
數(shù)據(jù)庫有一個字段ancestors存儲著部門父級id,每,用逗號分隔符隔開。比如:ancestors:“0,1,2,3,4,5,6,7,8,11,12,9,10,13"”,我需要查詢ancestors字段中包含“2”的信息
-- 表中數(shù)據(jù)示例
select * from `test`
結果:
使用 LIKE 模糊查詢
select * from `test` where ancestors like '%8';
結果:
使用 FIND_IN_SET 函數(shù) 【推薦】
使用 FIND_IN_SET 函數(shù)能夠準確查出 ancestors字段中含有 2 這項有哪些
select id,ancestors from `test` where find_in_set('2',ancestors) GROUP BY id;
結果:
使用 mysql 的正則表達式
我們在SQL中用WHERE子句搜索匹配的條件時,常用到LIKE關鍵字,今天來簡單介紹另一種更加強大的關鍵字: REGEXP, 正則匹配。
select id,ancestors from `test` where ancestors REGEXP '.*2';
結果:
使用 mysql 的LOCATE 函數(shù)
這個函數(shù),會把你查詢出含有查找 “ 2 ” 的數(shù)據(jù)文章來源:http://www.zghlxwxcb.cn/news/detail-680168.html
select id,ancestors from `test` where LOCATE ('2',ancestors);
結果:文章來源地址http://www.zghlxwxcb.cn/news/detail-680168.html
到了這里,關于Mysql 查詢以逗號(,)分割的字符串,精確查找和模糊查詢的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!