【MySQL】子查询,in ,exists(详解)

首先我们创建4张表:

在这里插入图片描述

现在我们用没有任何关键字的子查询来做到一下一点:

我们通过一个叫z1的同学找到她的班级然后通过她的班级Id找到她的班级名。
下面我们来编写代码:

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

这种查询是先执行内层查询,然后是外层查询。

然后我们来看如何用in 来完成子查询:

首先还是上面的4,
接下来我们完成一个任务,如何查询到z1和z3和z4的班级名。
接下来我们来完成代码

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)

in查询的内层查询可以返回多个结果,先执行的是内层查询。

最后我们来看如何用exists 来完成子查询:

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是有一个特点的,它是先执行外部查询,所以当我们内部使用class.classId的时候,它可以被数据库识别到。
如果我们这个用法用于in的话,是会报错的。

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

因为in首先执行内部,所以in内部的class.classId是无法被识别的。

猜你喜欢

转载自blog.csdn.net/weixin_54130714/article/details/123201108