检查字符串是否包含 MySQL 中的某些数据

在本教程中,我们旨在探索检查 MySQL 表中包含的字符串的不同方法。

我们将在 MySQL 中介绍以下技术。

  • INSTR 函数
  • LOCATE 函数
  • LIKE 运算符

然而,在我们开始之前,我们创建了一个虚拟数据集来使用。在这里,我们创建了一个表,student_details,以及其中的几行。

-- create the table student_details
CREATETABLEstudent_details(stu_idint,stu_firstNamevarchar(255)DEFAULTNULL,stu_lastNamevarchar(255)DEFAULTNULL,primarykey(stu_id));-- insert rows to the table student_details
INSERTINTOstudent_details(stu_id,stu_firstName,stu_lastName)VALUES(1,"Preet","Sanghavi"),(2,"Rich","John"),(3,"Veron","Brow"),(4,"Geo","Jos"),(5,"Hash","Shah"),(6,"Sachin","Parker"),(7,"David","Miller");

上面的查询创建了一个表以及其中包含学生名字和姓氏的行。为了查看数据中的条目,我们使用以下代码。

SELECT*FROMstudent_details;

上面的代码将给出以下输出。

stu_idstu_firstNamestu_lastName1PreetSanghavi2RichJohn3VeronBrow4GeoJos5HashShah6SachinParker7DavidMiller

让我们的目标是找到所有姓氏中包含 Parker 一词的学生。

使用 MySQL 中的 LOCATE 函数检查字符串是否包含 MySQL 中的某些数据

MySQL 中的 locate 函数一般有 2 个参数,比如 LOCATE(substr, str)。这里,substr 是作为第一个参数传入的子字符串,而 str 是作为第二个参数传入的字符串。LOCATE 函数的输出是出现作为参数传递的字符串的第一行。要查看此函数的运行情况,请查看下面的代码。

-- finding the word 'Park' from the table where the last name of the student is Park.
SELECT*FROMstudent_detailsWHERELOCATE('Park',stu_lastName)>0;

上面的代码将给出以下输出:

stu_id	stu_firstName	stu_lastName
6	      Sachin	      Parker

使用 MySQL 中的 INSTR 函数检查 MySQL 中的字符串是否包含某些数据

与 LOCATE 函数类似,INSTR 函数 INSTR(str, substr) 接受 2 个参数。但是,该函数返回字符串第一次出现在作为参数传入的子字符串中的索引值。这里,str 是作为第一个参数传入的字符串,而 substr 是作为第二个参数传入的子字符串。要查看此函数的运行情况,请查看下面的代码。

-- finding the word 'Park' from the table where the last name of the student is Park.
SELECT*FROMstudent_detailsWHEREINSTR(stu_lastName,'Parker')>0;

上面的代码将给出以下输出。

stu_idstu_firstNamestu_lastName6SachinParker
注意
LOCATE(substr,str)INSTR(str,substr) 函数中传递参数的方式是不同的。

使用 MySQL 中的 LIKE 运算符检查 MySQL 中的字符串是否包含某些数据

在数据中查找字符串是否存在的另一种替代方法是使用 LIKE。此运算符与 WHERE 子句一起使用以查找特定字符串。要查看此技术的实际效果,请查看下面的代码。

-- finding the word 'Park' from the table where the last name of the student is Parker.
SELECT*FROMstudent_detailsWHEREstu_lastNameLIKE'Parker';

上面的代码将再次给出以下输出。

stu_id	stu_firstName	stu_lastName
6	      Sachin	      Parker

此外,%,也称为通配符,也与 LIKE 运算符一起使用。顾名思义,这个通配符代表无、一个或多个字符。要查看此通配符的实际效果,请查看下面的代码。

-- finding the student with last name ending in 'arker' from the table.
SELECT*FROMstudent_detailsWHEREstu_lastNameLIKE'%arker';

上面的代码将再次给出以下输出。

stu_id	stu_firstName	stu_lastName
6	      Sachin	      Parker

因此,借助上述三种技术,我们可以有效地从表中找到字符串的存在。