MySQL 数据库中 IF EXISTS 的使用

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

然而,在我们开始之前,我们创建了一个虚拟数据集来使用。在这里,我们创建了一个表,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_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
SELECTcolumn_nameFROMtable_nameWHEREEXISTS(SELECTcolumn_nameFROMtable_nameWHEREcondition);

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

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

-- Here we save the output of the code as RESULT
SELECTEXISTS(SELECT*fromstudent_detailsWHEREstu_id=4)asRESULT;

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

RESULT
1

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

在 MySQL 中使用 IF EXISTS 运算符

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

SELECTIF(EXISTS(SELECTcolumn_nameFROMtable_nameWHEREcondition),1,0)

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

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

SELECTIF(EXISTS(SELECTstu_firstNameFROMstudent_detailsWHEREstu_id=4),'Yes, exists','No, does not exist')asRESULT;

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

RESULT
Yes, exists

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

SELECTIF(EXISTS(SELECTstu_firstNameFROMstudent_detailsWHEREstu_id=11),'Yes, exists','No, does not exist')asRESULT;
注意
我们使用 ALIAS RESULT 在输出代码块中显示我们的输出。

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

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

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