FIND_IN_SET(str,strlist)
官网阐明
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings.
A string list is a string composed of substrings separated by , characters.
If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic.
Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (,) character.
重点阐明:
- 查问字段 strlist 是否蕴含 str,如果包含返回 str 所在下标 (从 1 开始),否则返回 0.
- strlist 是一个字符串汇合通过, 宰割
- 当参数 str 或者 strlist 任何一个为 null 的时候后果返回 null
- str 参数不应该蕴含,
看几个示例
// 第二个数匹配
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2
// 依照, 宰割 没有匹配的
SELECT FIND_IN_SET('b','ab,c,d');
-> 0
// 宰割后 abc 和 ab 不匹配
SELECT FIND_IN_SET('ab','abc,ab,ss');
-> 2
// 多个匹配依照第一个匹配算
SELECT FIND_IN_SET('ab','abc,ab,ss,ab');
-> 2
一些我的项目中的理论利用
// 导入测试数据 用户善于的编程语言
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_language
-- ----------------------------
DROP TABLE IF EXISTS `user_language`;
CREATE TABLE `user_language` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`language` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of user_language
-- ----------------------------
BEGIN;
INSERT INTO `user_language` VALUES (1, 'aa', 'PHP,GO,JAVA');
INSERT INTO `user_language` VALUES (2, 'bb', 'C,GO');
INSERT INTO `user_language` VALUES (3, 'cc', 'RUST,PHP');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
// 查问善于 php 语言的用户
SELECT * from user_language where FIND_IN_SET('PHP',language)
参考
- https://dev.mysql.com/doc/ref…