首先我们新建两个数据库表
create table student( id int primary key auto_increment, name varchar(20), class int );
create table class( id int primary key auto_increment, class int );
然后我们在表中插入数据
1.内连接inner join
我们知道student表中class这一块对应着class表中的班级,但是我们没有用外键,下面是内连接的写法,
这里的inner join就是内连接,也可以省略inner而写作join
select * from student inner join class on class.id = student.class;
select * from student join class on class.id = student.class;
通过结果我们可以看到我们查到了六条记录,我们student表中明明有八条啊,那是因为七八这两条在class中没有对应的数据,所以只显示了前六条有数据的,这是内连接。相当于数学中的交集。
2.外链接之左链接left outer join或left join
select * from student left outer join class on class.id = student.class;
select * from student left join class on class.id = student.class;
可以看到,左链接是以左边的student表为主,student里的数据都有,左边没有对应的数据就补全null
3.外链接之右连接right outer join或right join
select * from student right outer join class on class.id = student.class;
select * from student right join class on class.id = student.class;
右连接则是反过来我们可以看到左边的表都查了出来,左边会补全null
4.全连接full join其中MySQL是不支持full join的,MySQL可以用union
select * from student left join class on class.id = student.class
select * from student left join class on class.id = student.class union select * from student right join class on class.id = student.class
这样就会把所有的数据都查询出来,相当于并集