HOWTO · MySQL

MySQL 中的 WHERE IN 语句

本文介绍如何在 MySQL 中使用 WHERE IN 子句。

本页内容

在本教程中,我们旨在探索如何在 MySQL 中使用 WHERE IN 子句。

MySQL 中有许多不同的数据过滤技术。IF ELSE、CASE 和 WHERE 语句就是这样的示例。让我们探索本文中 WHERE IN 子句的实现细节。

WHERE IN 子句帮助我们为数据过滤设置特定条件。它接受列名和要在其中找到值的集合。查询的 IN 部分有助于在定义的集合中查找值。

让我们了解这种方法是如何工作的。在开始之前,我们必须通过创建一个表 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

MySQL 中的 WHERE IN 语句

WHERE IN 技术的基本语法如下。

SELECT * FROM name_of_the_table WHERE column_name IN <set_condition>;

让我们尝试从 student_details 表中过滤学生。

我们只为 stu_id 小于 3 的学生获取记录。使用 WHERE IN 子句,此操作可以在以下查询的帮助下完成。

SELECT * FROM student_details WHERE stu_id IN (1,2,3);

输出:

stu_id	stu_firstName	stu_lastName
1	      Preet	        Sanghavi
2	      Rich	        John
3	      Veron	        Brow

如上面的代码块所示,我们仅根据需要获取具有 stu_id 为 1、2 或 3 的记录。

WHERE IN 技术的替代方法是 CASE WHEN 语句。IF ELSE 存储过程也可以用来代替 WHERE IN 子句。

因此,在带有 IN 的 WHERE 语句的帮助下,我们可以根据 MySQL 中的任何条目可用性条件有效地过滤数据。