MYSQL内连接和外连接例子
Mysql 内连接和外连接例子
解释名词:
1、内连接(自然连接):只有两个表相匹配的行才能在结果集中出现
2、外连接:包括
(1)左外连接(左边的表不加限制)
(2)右外连接(右边的表不加限制)
(3)全外连接(左右两表都不加限制)
3、创建student 、score 表如下
(student 表)
(score 表)
A :内连接sql
select st.student_name,sc.object,sc.score,st.student_class
from student st ,score sc where st.student_id=sc.student_id
执行结果:
这个大家一般都司空见惯了。所以没什么可讲。内连接只是显示满足where 后面的条件(st.student_id=sc.student_id)
B :左外连接sql
select st.student_name,sc.object,sc.score,st.student_class
from student st left join score sc on st.student_id=sc.student_id
执行结果:
左外连接是以左边的表(student st left )student 为主表,score 为从表。在查询结果中全部展示主表的信息。
也就出现上图中Tom 这个信息不全。因为从表中没有和Tom 相匹配的信息,因此才会出现Null 值填充。
C :右外连接
select st.student_name,sc.object,sc.score,st.student_class
from student st right join score sc on st.student_id=sc.student_id
执行结果:
右连接刚好和做连接想法。因此就会出现上图的情况。
D :全外连接sql
1. select st.student_name,sc.object,sc.score,st.student_class
from student st left join score sc on sc.student_id=st.student_id
union
select st.student_name,sc.object,sc.score,st.student_class
from student st RIGHT join score sc on sc.student_id=st.student_id
(本人使用mysql 数据库,因为mysql 暂时还不支持全外连接full 的功能,但是可以用多个left 来实现)
2.select st.student_name,sc.object,sc.score,st.student_class
from student st full join score sc on sc.student_id=st.student_id(此语句针对一般数据库)
解释名词:
1、内连接(自然连接):只有两个表相匹配的行才能在结果集中出现
2、外连接:包括
(1)左外连接(左边的表不加限制)
(2)右外连接(右边的表不加限制)
(3)全外连接(左右两表都不加限制)
3、创建student 、score 表如下
(student 表)
(score 表)
A :内连接sql
select st.student_name,sc.object,sc.score,st.student_class
from student st ,score sc where st.student_id=sc.student_id
执行结果:
这个大家一般都司空见惯了。所以没什么可讲。内连接只是显示满足where 后面的条件(st.student_id=sc.student_id)
B :左外连接sql
select st.student_name,sc.object,sc.score,st.student_class
from student st left join score sc on st.student_id=sc.student_id
执行结果:
左外连接是以左边的表(student st left )student 为主表,score 为从表。在查询结果中全部展示主表的信息。
也就出现上图中Tom 这个信息不全。因为从表中没有和Tom 相匹配的信息,因此才会出现Null 值填充。
C :右外连接
select st.student_name,sc.object,sc.score,st.student_class
from student st right join score sc on st.student_id=sc.student_id
执行结果:
右连接刚好和做连接想法。因此就会出现上图的情况。D
:全外连接sql
1. select st.student_name,sc.object,sc.score,st.student_class
from student st left join score sc on sc.student_id=st.student_id
union
select st.student_name,sc.object,sc.score,st.student_class
from student st RIGHT join score sc on sc.student_id=st.student_id
(本人使用mysql 数据库,因为mysql 暂时还不支持全外连接full 的功能,但是可以用多个left 来实现)
2.select st.student_name,sc.object,sc.score,st.student_class
from student st full join score sc on sc.student_id=st.student_id(此语句针对一般数据库)