对于两张表,外连接和内连接的区别在于:
内连接:只显示两表id匹配的
左外连接:显示join左边的表的所有数据(不管两表是否匹配),对于不匹配的部分都用NULL显示
右外连接:与左外连接相反,显示join右边的表的所有数据
我们直接用题来解释。

假设有两个表stu和exam,该表结构如上,我们要显示所有学生的成绩,那么内连接和外连接的方式分别为(插入数据请自己补全):
create table stu( Id int, Name varchar(40)) create table exam( Id int, Grade int) insert into exam values(11,89) select * from stu select * from exam --【显示所有学生的成绩】 --内连接(只显示两表id匹配的) select stu.id,exam.id,stu.name,exam.grade from stu inner join exam on stu.id=exam.id --左外连接(显示join左边的表的所有数据,exam只有两条记录,所以stu.id,grade都用NULL显示) select stu.id,exam.id,stu.name,exam.grade from stu left join exam on stu.id=exam.id --右外连接(与左外连接相反,显示join右边的表的所有数据) select stu.id,exam.id,stu.name,exam.grade from stu right join exam on stu.id=exam.id
对于插入完的数据查询结果应该是这样的:

1.如果用内连接显示所有学生的成绩, 那么他会只显示两表id匹配的

2.对于左外查询,他会显示join左边的表的所有数据,exam只有两条记录,所以stu.id,grade都用NULL显示

3.右连接与左连接相反,显示join右边的表的所有数据

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/176185.html原文链接:https://javaforall.net
