SQL表连接查询(inner join、full join、left join、right join)
有两个表,一个是班级表,一个是学生表。
class 表的数据
student 表的数据
一、内连接-inner jion :
查询学生的名字和所在班级的名字
select stu_name,class_name from student as s,class as c where c.class_no = s.class_no;
上面就是我们最常见的inner join,即内连接,把符合class.class_no = student.class_no条件的元组才选出来,也可以写成:
select stu_name,class_name from student as s inner join class as c on c.class_no=s.class_no;
查询结果
二、左连接-left join:
左连接是把左边的表的元组全部选出来:
select * from student s left join class c on s.class_no =c.class_no;
上面语句就是把左边的表,即student表中的元组全部选出,尽管有些学生在表中是没有班级的,也选了出来,选出的结果为:
三、右连接-right join:
右连接就是把右边表的数据全部取出,不管左边的表是否有匹配的数据:
select * from student s right join class c on s.class_no=c.class_no
四、全连接-full join:
把左右两个表的数据都取出来,不管是否匹配:
select * from student s full join class c on s.class_no = c.class_no;
好像不支持全连接
#建表及数据准备
drop table if exists class;
create table class(
class_no int(2) unsigned zerofill primary key auto_increment comment '班级编号',
class_name varchar(30) not null comment '班级名称'
);
insert into class values(1, '培优班');
insert into class values(2, '普通班');
insert into class values(3, '提升班');
insert into class values(4, '高级班');
drop table if exists student;
create table student(
stu_no int(2) unsigned zerofill primary key auto_increment comment '学员编号',
stu_name varchar(30) not null comment '学员姓名',
stu_sex varchar(3) not null comment '学员性别',
stu_age tinyint(2) unsigned zerofill comment '学员年代',
grade double(5,2) zerofill comment '成绩',
class_no int(2) unsigned zerofill comment '所在班级编号',
foreign key(class_no) references class(class_no)
);
insert into student values(01, '李白', '男', 18, 60, 01);
insert into student values(02, '杜甫', '男', 20, 76, 01);
insert into student values(03, '张飞', '男', 32, 80, 02);
insert into student values(04, '韩信', '男', 26, 98, 02);
insert into student values(05, '了龙', '男', 27, 56, 02);
insert into student values(06, '大乔', '女', 17, 88, 01);
insert into student values(07, '小乔', '女', 16, 96, 01);
insert into student values(08, '小乔', '女', 16, 90, 01);
insert into student values(09, '关哥', '男', 32, 80, 02);
insert into student values(10, '刘备', '男', 36, 98, null);
连接查询的分类
1: 内连接
2: 外连接
3: 自然连接