在 MySQL 数据库的集合中查找值
Preet Sanghavi 2023年1月30日 MySQL MySQL Database

在本教程中,我们旨在探索如何检查值的出现或在 MySQL 数据库的集合中查找值。
这可以借助 IN()
函数或 FIND_IN_SET()
函数来完成。让我们探索在 MySQL 数据库中使用 FIND_IN_SET()
函数。
FIND_IN_SET()
函数主要接受两个参数。第一个参数是要搜索的值,第二个参数是要搜索的值的集合。
这可以表示为 FIND_IN_SET("search", {search_here})
。让我们尝试在我们的 MySQL 服务器中使用这个函数。
在 MySQL 中创建表
在开始之前,我们将创建一个虚拟数据集来使用。在这里,我们将创建一个表 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
使用 FIND_IN_SET()
在 MySQL 数据库的集合中查找值
我们已经成功地创建了我们的表 student_details
并将其可视化。让我们尝试在 stu_firstName
集合中找到一个特定的名称。
执行上述任务的语法如下所示:
SELECT FIND_IN_SET("value_to_be_searched", {set});
在这里,我们可以看到,术语 value_to_be_searched
将被我们需要在表中查找的实际值替换。
让我们确定值 David
是否存在于 stu_firstName
列中。这可以在以下查询的帮助下完成:
SELECT FIND_IN_SET("David", stu_firstName) as boolean_here from student_details ;
上述代码的输出可以说明如下:
boolean_here 0 0 0 0 0 0 1
注意:注意此处使用的
AS
关键字作为别名很重要。我们使用别名使我们的查询更具可读性和全面性。
但是,此功能仅在 MySQL 4.0 及更高版本中可用。因此,我们已经成功理解了如何在 MySQL 中使用 FIND_IN_SET()
函数。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Preet Sanghavi