当前位置:   article > 正文

mysql数据库7种_Mysql的7种join解析

mysql 有多少join

Mysql的7种join,各种项目中,数据库经常用到,也是必不可少的,数据库查询中经常使用到两个表之间的查询甚至是多表之间的查询,以下列举了mysql的7种join语句。

建表语句

建两个表,有外键相关联的表。

create table user

(

id int primary key,

name char(11)

)engine=innodb;

create table role

(

rid int primary key,

rname char(11),

uid int,

constraint foreign key (uid) references user(id)

)engine=innodb;

insert into user values(1,'xiaohai');

insert into user values(2,'xiaolan');

insert into user values(3,'xiaoxiao');

insert into user values(4,'xiaolong');

insert into user values(5,'xiaolei');

insert into role values(1,'admin',1);

insert into role values(2,'user',2);

insert into role values(3,'vip1',3);

insert into role values(4,'vip2',4);

insert into role(rid,rname) values(5,'admin');

1.文氏图左外连接

20180817092801397.png

SQL语句

select u.*,r.* from user u left join role r on u.id = r.uid ;

查询结果:

20180817092801403.png

2.文氏图右外连接

20180817092802409.png

SQL语句

select u.*,r.* from user u right join role r on u.id = r.uid ;

查询结果

20180817092802413.png

3.文氏图左连接

20180817092802415.png

SQL语句:去掉表A表B都有的,单独显示表A的元素

select u.*,r.* from user u left join role r on u.id = r.uid where r.rid is null;

查询结果

20180817092802419.png

4.文氏图右连接

20180817092802424.png

SQL语句

select u.*,r.* from user u right join role r on u.id = r.uid where u.id is null;

查询结果

20180817092802432.png

5.文氏图内连接

20180817092802436.png

sql语句

select u.*,r.* from user u inner join role r on u.id = r.uid;

查询结果

20180817092802444.png

6.全连接:oracle数据库有full join ...on语句,mysql没有。

20180817092803446.png

SQL语句

select u.*,r.* from user u left join role r on u.id = r.uid where r.rid is null

union

select u2.*,r2.* from user u2 right join role r2 on u2.id = r2.uid;

查询结果

20180817092803448.png

7.两张表中都没有出现的数据集:就是两张表各自独立的那部分数据集,没有相同部分的数据集。

文氏图

20180817092803451.png

SQL语句

select u.*,r.* from user u left join role r on u.id = r.uid where r.rid is null

union

select u2.*,r2.* from user u2 right join role r2 on u2.id = r2.uid where u2.id is null;

查询结果

20180817092803452.png

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/1020596
推荐阅读
相关标签
  

闽ICP备14008679号