MySQL之join语句

介绍

join用于多表中字段之间的联系,语法如下

...from table1 inner|left|right join table2 on...

首先建表 
这里写图片描述 
这里写图片描述

1、inner join

基于连接谓词将两张表的列组合在一起,产生新的结果表

select * from user1 inner join user2 on user1.user_name=user2.user_name;

这里写图片描述 
这里写图片描述

2、left join

从左表产生一套完整的记录,还有右边匹配的记录,如果没有匹配就包含null

这里写图片描述

select * from user1 left join user2 on user1.user_name=user2.user_name;

这里写图片描述

只查询左表的数据,不包含右表的,使用where 限制右表key为null

select * from user1 left outer join user2 on user1.user_name=user2.user_n
ame where user2.user_name is null;

这里写图片描述

使用left join实现inner join的效果

使用where 限制左右表key不为null

select * from user1 left outer join user2 on user1.user_name=user2.user_n
ame where user1.user_name is not null and user2.user_name is not null;
  • 这里写图片描述

求差集

就求除重合的其他全部

mysql> select * from user1 left join user2 on user1.user_name=user2.user_name
    -> where user2.id is null
    -> union
    -> select * from user1 right join user2 on user1.user_name=user2.user_name
    -> where user1.id is null;

这里写图片描述 
这里写图片描述

3、right join

这里写图片描述

select * from user1 right join user2 on user1.user_name=user2.user_name;

这里写图片描述

4、cross join

交叉连接,得到的结果是两个表的乘积,即笛卡尔积

 select * from user1 cross join user2;
  • 这里写图片描述

再试一下 select * from user1 inner join user2; 
这里写图片描述 
可以看出在MySQL cross join、inner join、join这三者实现效果一样

5、full join

full join的实现使用左连接和右连接一起实现,如果没匹配,对面就null

mysql> select * from user1 left join user2 on user1.user_name=user2.user_name
    -> union
    -> select * from user1 right join user2 on user1.user_name=user2.user_name;

这里写图片描述 
这里写图片描述

6、3个或者3个以上表间的连接

 select * from(
 user1 inner join user2 on user1.user_name=user2.user_name
 )
 inner join user_kills;

括号里面的SQL语句可以看成一个表,然后又使用inner join….on连接起来的两个或者多个表,作为新表与其他表进行连接 
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_36142114/article/details/80476629