解释名词:
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(此语句针对一般数据库)