目录
2、POSITION( substring IN string )
一、说明:
涉及场景:判断表当前行,字段1的数据是否包含在字段2中数据
效果演示:
二、涉及/可用函数:
1、INSTR(str,substr)
1)INSTR()函数接受2个参数:str是要搜索的字符串;substr是要搜索的子字符串。
2)INSTR()函数返回字符串中子字符串第1次出现的位置。如果在str中找不到子字符串,则INSTR()函数返回零(0)。
3)INSTR()函数不区分大小写。如果希望INSTR函数在非二进制字符串上以区分大小写的方式执行搜索,则可以使用BINARY运算符将INSTR函数的参数从非二进制字符串转换为二进制字符串。
4)举例:字段1为:小明 、字段2为小明爸爸,字段2包含字段1
-- 判断字段(name)是否在字段(explain)内
SELECT *,if(INSTR(`explain`,`name`),'是','否') as 是否包含
from ceshi1;
-- 查询出字段(explain)包含字段(name)的表信息
SELECT * from ceshi1
where INSTR(`explain`,`name`);
-- where INSTR(`name`,`explain`); 字段对调查询
2、POSITION( substring IN string )
1)position()函数接受3个参数:substring 要在string中搜索的子字符串; string 要搜索的字符串; start_position 可选的。用于指定从string中哪个位置开始查找。默认为1,即字符串中的第一个位置。
2)position()函数如果在string中找不到substring,则POSITION函数将返回0。
3)position()函数不区分大小写的。 POSITION函数和LOCATE函数的作用是一样的。
4)举例:字段1为:小明 、字段2为小明爸爸,字段2包含字段1
-- 判断字段(name)是否在字段(explain)内
SELECT *, if(POSITION(`name` in `explain`),'是','否') as 是否包含
from ceshi1;
-- 查询出字段(explain)包含字段(name)的表信息
SELECT * from ceshi1
where POSITION(`name` in `explain`);
-- where POSITION(`explain` in `name`); 字段对调查询
3、LOCATE (substring; string)
1)LOCATE ()函数中,substring 是要在字符串 string 中搜索的字符串,而 string 是可能包含substring 的字符串。
2)LOCATE ()函数将返substring 在 string 中第1次出现的位置。如果没有找到 substring,则该函数将返回0。
3)要查找一个或多个 (ARE) 指定的单个字符串,可以使用另一个常见的
4)举例:字段1为:小明 、字段2为小明爸爸,字段2包含字段1
-- 判断字段(name)是否在字段(explain)内
SELECT *, if(LOCATE(`name`,`explain`),'是','否') as 是否包含
from ceshi1;
-- 查询出字段(explain)包含字段(name)的表信息
SELECT * from ceshi1
where LOCATE(`name`,`explain`);
-- where LOCATE(`explain`,`name`);字段对调查询
4、正则表达式regexp
1)包含判断会有出入,互为模糊判断
2)举例:字段1为:小明 、字段2为小明爸爸,字段2包含字段1
或 字段1为:小张三三 、字段2为:三三个小张
SELECT * from ceshi1
where `explain` regexp (SELECT GROUP_CONCAT(name SEPARATOR '|') from ceshi1) ;
regexp效果展示
建测试表语句
-- 建测试表
DROP TABLE if EXISTS `ceshi1`;
CREATE TABLE `ceshi1` (
`id` int auto_increment primary key,
`name` VARCHAR(10),
`explain` VARCHAR(10)
);
INSERT into `ceshi1` VALUES('1','小明','no!小明不爱学习');
INSERT into `ceshi1` VALUES('2','小明','小不乖明');
INSERT into `ceshi1` VALUES('3','小张的','三三个小张');
INSERT into `ceshi1` VALUES('4','小张','小没有张');
INSERT into `ceshi1` VALUES('5','小张','校长是小张他爸爸');
INSERT into `ceshi1` VALUES('6','小张','小张');
INSERT into `ceshi1` VALUES('7','小张','三三个');
INSERT into `ceshi1` VALUES('8','小张三三','三三个小张');
INSERT into `ceshi1` VALUES('9','小明','不是的,他不是小明');