内连接查询
- 仅将两个表中满足连接条件的行组合起来作为结果集,称为内连接;
- 关键字:
[inner] join ... on
。
语法:
表1 [inner] join 表2 on 表1.字段=表2.字段
查询数据表中学生姓名以及对应的班级名称,将其对应的列名分别另命名为studentName
和className
。
tb_student
表数据:
id | name | class_id |
---|---|---|
1 | Emma | 2 |
2 | Mary | 4 |
3 | Allen | (null) |
4 | Kevin | 1 |
5 | Rose | 2 |
6 | James | 1 |
tb_class
表数据:
id | name |
---|---|
1 | 软件1631 |
2 | 软件1632 |
3 | 测试1631 |
4 | 测试1632 |
select tb_student.name as studentName,tb_class.name as className from tb_student join tb_class on tb_student.class_id = tb_class.id;
外连接查询
- 以某张表为主,取出里面的所有记录,然后每条与另外一张表进行连接,不管能不能匹配上条件,最终都会保留。能匹配,正确保留;不能匹配,其它表的字段都置空(
null
),称为外连接。 - 外连接查询分为左外连接查询和右外连接查询;
- 关键字:
left/right [outer] join ... on
。
语法:
表1 left/right [outer] join 表2 on 表1.字段=表2.字段
示例
分别使用左外连接
和右外连接
查询数据表中所有学生姓名和对应的班级名称,查询结果列分别另命名为studentName
和className
。
我们为你提供了两张表,内容如下:
tb_student
表数据:
id | name | class_id |
---|---|---|
1 | Emma | 2 |
2 | Mary | 4 |
3 | Allen | (null) |
4 | Kevin | 1 |
5 | Rose | 2 |
6 | James | 1 |
tb_class
表数据:
id | name |
---|---|
1 | 软件1631 |
2 | 软件1632 |
3 | 测试1631 |
4 | 测试1632 |
注意:请使用 tb_student 作为左表,tb_class 作为右表。
select tb_student.name as studentName,tb_class.name as className from tb_student left join tb_class on tb_student.class_id = tb_class.id;
select tb_student.name as studentName,tb_class.name as className from tb_student right join tb_class on tb_student.class_id = tb_class.id;
复合条件连接查询
- 复合条件连接查询,就是在连接查询的过程中,通过添加过滤条件来限制查询结果,使查询结果更加精确。
查询所有班级里分数在90
分以上的学生的姓名和学生的成绩以及学生所在的班级,其中学生的姓名和学生所在班级分别另命名为studentName
和className
。
我们为你提供了两张表,内容如下:
tb_student
表数据:
id | name | class_id | score |
---|---|---|---|
1 | Emma | 2 | 89 |
2 | Mary | 4 | 92 |
4 | Kevin | 1 | 76 |
5 | Rose | 3 | 68 |
6 | James | 1 | 99 |
tb_class
表数据:
id | name |
---|---|
1 | 软件1631 |
2 | 软件1632 |
3 | 测试1631 |
4 | 测试1632 |
select tb_student.name as studentName,tb_student.score,tb_class.name as className from tb_student join tb_class on tb_student.class_id = tb_class.id where tb_student.score > 90;