检查字符串是否包含 MySQL 中的某些数据
在本篇文章中,我们旨在探索检查 MySQL 表中包含的字符串的不同方法。
我们将在 MySQL 中介绍以下技术。
-
INSTR
函数 -
LOCATE
函数 -
LIKE
运算符
然而,在我们开始之前,我们创建了一个虚拟数据集来使用。在这里,我们创建了一个表,student_details
,以及其中的几行。
-- create the table student_details
CREATE TABLE student_details(
stu_id int,
stu_firstName varchar(255) DEFAULT NULL,
stu_lastName varchar(255) DEFAULT NULL,
primary key(stu_id)
);
-- insert rows to the table student_details
INSERT INTO student_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 * FROM student_details;
上面的代码将给出以下输出。
stu_id stu_firstName stu_lastName
1 Preet Sanghavi
2 Rich John
3 Veron Brow
4 Geo Jos
5 Hash Shah
6 Sachin Parker
7 David Miller
让我们的目标是找到所有姓氏中包含 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 * FROM student_details WHERE LOCATE('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 * FROM student_details WHERE INSTR(stu_lastName , 'Parker') > 0;
上面的代码将给出以下输出。
stu_id stu_firstName stu_lastName
6 Sachin Parker
使用 MySQL 中的 LIKE 运算符检查 MySQL 中的字符串是否包含某些数据
在数据中查找字符串是否存在的另一种替代方法是使用 LIKE
。此运算符与 WHERE
子句一起使用以查找特定字符串。要查看此技术的实际效果,请查看下面的代码。
-- finding the word 'Park' from the table where the last name of the student is Parker.
SELECT * FROM student_details WHERE stu_lastName LIKE 'Parker' ;
上面的代码将再次给出以下输出。
stu_id stu_firstName stu_lastName
6 Sachin Parker
此外,%
,也称为通配符,也与 LIKE 运算符一起使用。顾名思义,这个通配符代表无、一个或多个字符。要查看此通配符的实际效果,请查看下面的代码。
-- finding the student with last name ending in 'arker' from the table.
SELECT * FROM student_details WHERE stu_lastName LIKE '%arker' ;
上面的代码将再次给出以下输出。
stu_id stu_firstName stu_lastName
6 Sachin Parker
因此,借助上述三种技术,我们可以有效地从表中找到字符串的存在。
相关文章
如何在 MySQL 中声明和使用变量
发布时间:2024/03/26 浏览次数:115 分类:MySQL
-
当你需要在 MySQL 中的脚本中存储单个值时,最好的方法是使用变量。变量有不同的种类,有必要知道何时以及如何使用每种类型。
在 MySQL 中使用 Mysqladmin 刷新主机解除阻塞
发布时间:2024/03/26 浏览次数:82 分类:MySQL
-
你将了解阻止主机的原因。此外,通过使用 phpMyAdmin 和命令提示符刷新主机缓存来解除阻塞的不同方法和效果。