一文详述Mysql left join、 right join、 inner join、 join使用及其区别

序言

Mysql多表之间的关联分为以下几种情况:

left join 、right join、inner join、join 、“,” 使用不同的关联关系可能得到不同的结果,我们知道2表直接的关联可能会使结果条数增多或减少,下面我们通过2张表进行说明,为了使结果比较明显,构造数据的时候,在2张表中互相存在关联不上的数据,也就是表1中的某条数据在表2中关联不上,表2中存在某条数据在表1中关联不上。

正文

准备工作

创建2中表:科目表(subject) 、分数表(score)

create table subject
(
    id      int         not null
        primary key,
    subject varchar(10) null comment '科目'
);
create table score
(
    id         int           not null
        primary key,
    score      int default 0 null comment '分数',
    subject_id int           not null comment '科目ID'
);

插入初始化数据

insert into school.subject (id, subject)
values  (1, '语文'),
        (2, '数学'),
        (3, '英语');
insert into school.score (id, score, subject_id)
values  (1, 10, 1),
        (2, 10, 1),
        (3, 30, 2),
        (4, 50, 5);

left join

使用left join关联2个表,通过科目ID 

select subject.*,s.* from subject left join score s on subject.id = s.subject_id;

执行结果:

 说明:

1、若左表数据存在,右表数据不存在,那么会以左边数据为根据,右表相应的字段为null 
2、会产生笛卡尔积,若左边数据在右边数据中关联了2条,那么结果会存在2条左表数据 ,即结果会存在4条数据,比左表数据多一条

left join key is null

select subject.* , s.* from subject left join score s on subject.id = s.subject_id where isnull(subject_id);

执行结果:

说明:会将结果中subject_id不为空的数据过滤掉,这样可以将结果分成3类,1、包含所有的笛卡尔积结果 2、使用isnull 函数,包含数据存在左表,但是不存在右表的数据 3、使用!isnull 函数 ,包含数据即存在左右表都存在的数据

right join

select subject.*,s.* from subject right outer join score s on subject.id = s.subject_id;

执行结果 :

说明:

1、若右表数据存在,左表数据不存在,那么会以右表数据为根据,左表相应的字段为null 
2、会产生笛卡尔积,若右表数据在左表中关联了相同一条数据,那么结果中右表数据的2条数据会关联同一条左表数据,结果中出现2条都是语文的数据,右表存在4条数据,其中一条数据在左表中不存在,那么左表对应的字段为null,而左表中的英语则不会出现的结果中

right join key is null

select subject.* , s.* from subject right  join score s on subject.id = s.subject_id where isnull(subject.subject);

执行结果:

 说明:会将结果中subject.subject不为空的数据过滤掉,这样可以将结果分成3类,

1、包含所有的笛卡尔积结果

2、使用isnull 函数,包含数据存在右表,但是不存在左表的数据

3、使用!isnull 函数 ,包含数据在左右表都存在的数据

join 

select subject.*,s.* from subject join score s on subject.id = s.subject_id;

 执行结果:

说明:只会保留在2表中都存在的数据 相当于上述中 "!isnull" 的结果,即表中不存在null的行

inner join

select subject.*,s.* from subject inner join score s on subject.id = s.subject_id;

 执行结果:

 说明:其实就是 Join的写法

俩表通过","关联

select subject.*,s.* from subject , score s order by subject.id;

 运行结果:

说明:会产生笛卡尔积 3 * 4 = 12 条数据

 将俩表互换,通过","关联

select subject.*,s.* from score s , subject order by subject.id;

说明:执行结果与上面相同,说明通过","关联,与左右位置无关

猜你喜欢

转载自blog.csdn.net/zanpengfei/article/details/124328146