【MySQL】内部結合、外部結合、自己結合(詳細説明)

まず、内部結合を使用することも表1 join 表2on 条件表1 别名1 join 表2 别名2 on 条件使用することもできます。from表1,表2

まず 2 つのテーブルを作成しましょう。

ここに画像の説明を挿入

次に、内部接続と外部接続を理解しましょう。

ここに画像の説明を挿入

下面是内连接
mysql> select student.name,class.className from student join class on student.classId = class.classId;
+------+-----------+
| name | className |
+------+-----------+
| z1   | c1        |
| z2   | c2        |
| z3   | c3        |
+------+-----------+
3 rows in set (0.00 sec)
mysql> select stu.name,cla.className from student stu join class cla on stu.classId = cla.classId;
+------+-----------+
| name | className |
+------+-----------+
| z1   | c1        |
| z2   | c2        |
| z3   | c3        |
+------+-----------+
3 rows in set (0.00 sec)
下面是左外连接
mysql> select student.name,class.className from student left join class on student.classId = class.classId;
+------+-----------+
| name | className |
+------+-----------+
| z1   | c1        |
| z2   | c2        |
| z3   | c3        |
| z4   | NULL      |
| z5   | NULL      |
+------+-----------+
5 rows in set (0.00 sec)
mysql> select stu.name,cla.className from student stu left join class cla on stu.classId = cla.classId;
+------+-----------+
| name | className |
+------+-----------+
| z1   | c1        |
| z2   | c2        |
| z3   | c3        |
| z4   | NULL      |
| z5   | NULL      |
+------+-----------+
5 rows in set (0.00 sec)
下面是右外连接
mysql> select student.name,class.className from student right join class on student.classId = class.classId;
+------+-----------+
| name | className |
+------+-----------+
| z1   | c1        |
| z2   | c2        |
| z3   | c3        |
| NULL | c99       |
| NULL | c88       |
+------+-----------+
5 rows in set (0.00 sec)
mysql> select stu.name,cla.className from student stu right join class cla on stu.classId = cla.classId;
+------+-----------+
| name | className |
+------+-----------+
| z1   | c1        |
| z2   | c2        |
| z3   | c3        |
| NULL | c99       |
| NULL | c88       |
+------+-----------+
5 rows in set (0.00 sec)

次に、自己結合を見てみましょう. 自己結合テーブルはそれ自体です、つまり、それ自体とそれ自体の組み合わせです:
テーブルを作成しましょう:
ここに画像の説明を挿入

mysql> select * from studentscore as ss1,studentscore as ss2
    -> where ss1.studentId = ss2.studentId
    -> and ss1.courseId = 1
    -> and ss2.courseId = 3
    -> and ss1.score< ss2.score;
+-----------+-------------+----------+------------+-------+-----------+-------------+----------+------------+-------+
| studentId | studentName | courseId | courseName | score | studentId | studentName | courseId | courseName | score |
+-----------+-------------+----------+------------+-------+-----------+-------------+----------+------------+-------+
|         3 | z3          |        1 | chinese    |    45 |         3 | z3          |        3 | english    |    89 |
+-----------+-------------+----------+------------+-------+-----------+-------------+----------+------------+-------+
1 row in set (0.00 sec)

おすすめ

転載: blog.csdn.net/weixin_54130714/article/details/123181667