左连接,右连接,内连接,全连接的区别及使用

左连接,右连接,内连接,全连接的区别及使用

众所周知,我们在写sql时经常会用到多表查询数据,这就是涉及到连接的问题包括,左连接,右连接,内连接,全外连接。

定义:

左连接 (left join):返回包括左表的所有记录和右表中连接字段相等的记录

右连接(right join):返回包括右表的所有记录和左表中连接字段相等的记录

等值连接或者叫内连接(inner join):只返回两表相连相等的行

全外连接(full join):返回左右表中所有的记录和左右表中连接字段相等的记录。

只说概念还不够清晰举个例子就懂了!

A表:
  
id      name     
1       张三
2       李四
3       王五
B表;
   
id      A_id       class
1       1          一年一班
2       4          一年二班 

如上有两张表A表为学生表存id和姓名,B表为班级表存id,学生id,班级名。

来吧,展示

内连接:(只有2张表匹配的行才能显示)

select a.name,b.class from A a inner join B b on a.id=b.A_id

所以只能显示相连相等的行及A表id为1和B表A_id为一的

name   class
张三    一年一班

左连接:

select a.name,b.class from A a left join B b on a.id-b.A_i`在这里插入代码片`d

左表只有三条就显示三条 和右表没有相等字段补bull

name     class
张三     一年一班
李四     null
王五     null

右连接

select a.name,b.class from A a right join B b on a.id=b.A_id

右表只有两条就显示两条 和左表没有相等字段补null

name     class
张三     一年一班
null     一年二班

全连接

select a.name,b.class from A a full join B b on a.id=b.A_id

全部显示

name      class
张三      一年一班
null      一年二班
李四      null
王五      null

难度在高一点就是嵌套连接,去连接连接之后的新表等等。好好研究吧

猜你喜欢

转载自blog.csdn.net/qq_44772660/article/details/112675699