MySQL 数据库中 IF EXISTS 的使用

Preet Sanghavi 2023年1月30日
  1. MySQL 中 EXISTS 运算符的基本用法
  2. 在 MySQL 中使用 IF EXISTS 运算符
MySQL 数据库中 IF EXISTS 的使用

在本教程中,我们旨在探索 MySQL 中的 IF EXISTS 语句。

然而,在我们开始之前,我们创建了一个虚拟数据集来使用。在这里,我们创建了一个表,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 中 EXISTS 运算符的基本用法

MySQL 中的 EXISTS 条件通常与包含要满足的条件的子查询一起使用。如果满足此条件,则子查询至少返回一行。此方法可用于 DELETESELECTINSERTUPDATE 语句。

-- Here we select columns from the table based on a certain condition
SELECT column_name  
FROM table_name  
WHERE EXISTS (  
    SELECT column_name   
    FROM table_name   
    WHERE condition  
);  

此处,condition 表示从特定列中选择行时的过滤条件。

要检查 stu_firstName 列中是否存在 stu_id = 4 的学生,我们将使用以下代码:

-- Here we save the output of the code as RESULT
SELECT EXISTS(SELECT * from student_details WHERE stu_id=4) as RESULT;  

上述代码将给出以下输出:

RESULT
1

上面代码块中的 1 代表一个布尔值,这表明有一个学生的 stu_id = 4。

在 MySQL 中使用 IF EXISTS 运算符

有时,我们希望检查表中特定值的存在,并根据该条件的存在更改我们的输出。此操作的语法如下:

SELECT IF( EXISTS(
             SELECT column_name
             FROM table_name
             WHERE condition), 1, 0)

此处,如果 IF 语句返回 True,则查询的输出为 1。否则,它返回 0。

如果表中存在具有 stu_id=4 的学生,让我们编写一个返回 Yes, exists 的查询。否则,我们要返回不,不存在。要执行此操作,请查看以下代码:

SELECT IF( EXISTS(
             SELECT stu_firstName
             FROM student_details
             WHERE stu_id = 4), 'Yes, exists', 'No, does not exist') as RESULT;

上述代码将给出以下输出:

RESULT
Yes, exists

现在,让我们尝试查找 stu_id = 11 的学生。可以使用以下查询执行此操作:

SELECT IF( EXISTS(
             SELECT stu_firstName
             FROM student_details
             WHERE stu_id = 11), 'Yes, exists', 'No, does not exist') as RESULT;
注意
我们使用 ALIAS RESULT 在输出代码块中显示我们的输出。

上述代码将给出以下输出:

RESULT
No, does not exist
注意
通常,在 MySQL 中使用 EXISTS 方法的 SQL 查询非常慢,因为子查询会针对外部查询表中的每个条目重新运行。有更快、更有效的方法来表达大多数查询而不使用 EXISTS 条件。

因此,我们已经成功地在 MySQL 中实现了 IF EXISTS

作者: Preet Sanghavi
Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

相关文章 - MySQL Query