mysql中FIND_IN_SET方法学习

在mysql中,有时我们在做数据库查询时,需要得到某字段中包含某个值的记录,但是它也不是用like能解决的,使用like可能查到我们不想要的记录,它比like更精准,这时候mysql的FIND_IN_SET函数就派上用场了,下面来具体了解一下

官方对此函数的说明

  • 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.

大致翻译如下:

如果字符串str在由N个子字符串组成的字符串列表strlist中,则返回1到N范围内的值。 字符串列表是由字符组成的字符串,字符串之间用","分隔。 如果第一个参数是常量字符串,第二个参数是SET类型的列,则FIND_IN_SET()函数优化为使用位运算。 如果str不在strlist中或如果strlist是空字符串,则返回0。 如果任一参数为NULL,则返回NULL。 如果第一个参数包含逗号(,)字符,此函数无法正常工作。

例如:

mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2

示例:

CREATE TABLE `textbook` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(500) NOT NULL,
  `path_ids` VARCHAR(500) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
insert into `textbook` (`id`, `name`, `path_ids`) values('1','6. 静夜思','1,2,3');
insert into `textbook` (`id`, `name`, `path_ids`) values('2','7. 小小的船','2,3,5');
insert into `textbook` (`id`, `name`, `path_ids`) values('4','10. 比尾巴','3,9,5');
SELECT * FROM textbook WHERE FIND_IN_SET('3', path_ids);

使用in、find_in_set按顺序查出来

SELECT * FROM textbook WHERE id IN(3,1,4,2) ORDER BY FIND_IN_SET(id,'3,1,4,2');

mysql所有方法和操作符

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容