[MySQL] Subquery, in, exists (detailed explanation)

First we create 4 tables:

insert image description here

Now we do this with a subquery without any keywords:

We find her class by a classmate named z1 and find her class name by her class Id.
Let's write the code below:

mysql> select className from class where classId =
    -> (select studentClassId from student where studentName = 'z1');
+-----------+
| className |
+-----------+
| 计算机1|
+-----------+
1 row in set (0.00 sec)

This kind of query is to execute the inner query first, and then the outer query.

Then let's see how to use in to complete the subquery:

First of all, the above 4,
and then we complete a task, how to query the class names of z1, z3 and z4.
Next let's complete the code

mysql> select className from class where classId in
    -> (select studentClassId from student where studentName = 'z1'
    -> or studentName = 'z3'
    -> or studentName = 'z4');
+-----------+
| className |
+-----------+
| 计算机1|
| 计算机2|
| 计算机3|
+-----------+
3 rows in set (0.00 sec)

The inner query of the in query can return multiple results, and the inner query is executed first.

Finally, let's see how to use exists to complete the subquery:

mysql> select * from class where exists
    -> (select studentName from student where student.studentClassId =
    -> class.classId
    -> and student.studentClassId !=4);
+---------+-----------+
| classId | className |
+---------+-----------+
|       1 | 计算机1|
|       2 | 计算机2|
|       3 | 计算机3|
|       5 | 软件2|
|       6 | 大数据1|
|       7 | 大数据2|
+---------+-----------+
6 rows in set (0.00 sec)

exists has a feature, it executes the external query first, so when we use class.classId internally, it can be recognized by the database.
If our usage is used in in, an error will be reported.

mysql> select * from class where in
    -> (select studentClassId from student where student.studentClassId =
    -> class.classId
    -> and student.studentClassId !=4);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'in
(select studentClassId from student where student.studentClassId =
class.clas' at line 1

Because in is first executed internally, the class.classId inside in cannot be recognized.

Guess you like

Origin blog.csdn.net/weixin_54130714/article/details/123201108