在mysql中站欺,有時我們在做數(shù)據(jù)庫查詢時,需要得到某字段中包含某個值的記錄甜癞,但是它也不是用like能解決的爷怀,使用like可能查到我們不想要的記錄,它比like更精準带欢,這時候mysql的FIND_IN_SET函數(shù)就派上用場了,下面來具體了解一下
官方對此函數(shù)的說明
- 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范圍內(nèi)的值乔煞。 字符串列表是由字符組成的字符串,字符串之間用","分隔柒室。 如果第一個參數(shù)是常量字符串渡贾,第二個參數(shù)是SET類型的列,則FIND_IN_SET()函數(shù)優(yōu)化為使用位運算雄右。 如果str不在strlist中或如果strlist是空字符串空骚,則返回0纺讲。 如果任一參數(shù)為NULL,則返回NULL囤屹。 如果第一個參數(shù)包含逗號(熬甚,)字符,此函數(shù)無法正常工作肋坚。
例如:
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');