概述
join主要用于将不同的表可以根据某些指定的字段进行连接操作.
数据准备
- 学生表(student): 这里只展示了部分学生还有表中的字段.
- 课程表(course): 同上
- 分数表(score): 同上学生id, 课程id, 学生分数score
- 老师表(teacher):
内连接(join)=(inner join)
需求: 展示每个老师所讲的课程.(course)(teacher)
等值连接
select * from course c
join teacher t
on c.tea_id=t.tea_id;
如图所示: 根据tea_id字段将两个表进行连接为一个虚拟表.可以根据自己需要的字段进行输出.
不等值连接
select * from course c
join teacher t
on c.tea_id>t.tea_id; --这里的大于可以替换为<,!=...
左外连接(left join)
注意:你所需要的表是哪个.
select * from course c
left join teacher t
on c.tea_id=t.tea_id;
右外连接(right join)
解释: 同上
select * from course c
right join teacher t
on c.tea_id=t.tea_id;
满外连接(full join)
select * from course c
full join teacher t
on c.tea_id=t.tea_id;
多表连接
就是将多个表进行join连接
select stu.stu_id,stu.stu_name,stu.birthday,stu.sex,sc.course_id,ci.course_name from student stu
join score sc on stu.stu_id=sc.stu_id
join course ci on sc.course_id=ci.course_id;
--如果需要老师,还可以join(teacher)表
笛卡尔集
它会产生大量的数据.(一般不会用)
可能产生的原因:
- 没有连接条件
select * from a join b;- 连接条件无效
例子:
形式1:
select * from course join teacher;
形式2:
select * from course,teacher;
联合(union & union all)
作用: 将多张表的数据进行上下拼接.
前提: 多个表的字段个数需要相同,且类型也许相同.
union: 去重
union all: 不去重
select * from teacher where tea_id=1001
union
select * from teacher where tea_id=1002;
它连接的是多个select的查询语句.