内外连接
1.熟悉表连接的几种方式
2.熟悉几种表连接的区别
3.掌握多表连接查询【重点】
什么是表连接?
表连接(JOIN)是在多个表之间通过一定的连接条件,使表之间发生关联,进而能使多个表之间获取数据。
【重点】内连接取交集
【重点】左连接,把没有成绩的也显示出来
表连接语法:
select table1.column,table2.column
from table1,table2
where table1.column=table2.column;
内连接取交集
select A.c1,B.c2
from A join B
on A.c3=B.c3
左连接
select A.c1,B.c2
from A left join B
on A.c3=B.c3
|---------------------------------------------------------------------------------------------------------------------
开始实操
我们只需要掌握内连接和左连接,想当于掌握了内外连接了,基本可以解决我们的
应用需求了。
创建学生表和分数表,插入数据
drop table if exists score;
drop table if exists student;
create table student(
stu_no varchar(20) not null primary key comment '学号',
name varchar(30) comment '姓名',
address varchar(150) comment '地址'
);
insert into student(stu_no, name, address) values('2016001', '张三', '贵州贵阳');
insert into student(stu_no, name, address) values('2016002', '李芳', '陕西兴平');
insert into student(stu_no, name, address) values('2016003', '张晓燕', '江西南昌');
create table score(
id int not null auto_increment primary key,
course varchar(50) comment '科目',
stu_no varchar(20) comment '学号',
score int comment '分数',
foreign key(stu_no) references student(stu_no)
);
insert into score(course, stu_no, score) values('计算机', '2016001', 99);
insert into score(course, stu_no, score) values('离散数学', '2016001', 85);
insert into score(course, stu_no, score) values('计算机', '2016002', 78);
mysql> select A.stu_no,A.name,B.course,B.score from student A join score B on A.stu_no=B.stu_no;
和下面的语句等价
mysql> select A.stu_no,A.name,B.course,B.score from student A,score B where A.stu_no=B.stu_no;
左连接,不管这个人有没有成绩,都把结果显示出来。
mysql> select A.stu_no,A.name,B.course,B.score from student A left join score B on A.stu_no=B.stu_no;
交叉连接,没有添加where连接条件,产生笛卡尔积,实际应用上没什么意义,应该避免
mysql> select A.stu_no,A.name,B.course,B.score from student A join score B