1. 程式人生 > >Mysql的7種join

Mysql的7種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.文氏圖左外連線

SQL語句

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

查詢結果:

2.文氏圖右外連線

SQL語句

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

查詢結果

 

3.文氏圖左連線

SQL語句:去掉表A表B都有的,單獨顯示錶A的元素

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

查詢結果

 

4.文氏圖右連線

SQL語句

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

查詢結果

 

5.文氏圖內連線

sql語句

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

查詢結果

 

6.全連線:oracle資料庫有full join ... on語句,mysql沒有。

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;

查詢結果

 

7.兩張表中都沒有出現的資料集:就是兩張表各自獨立的那部分資料集,沒有相同部分的資料集。

文氏圖

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;

查詢結果