mysql 多表连接问题

mysql 连接有 外链接(左连接和右连接),内连接,交叉连接(笛卡尔积)。

基于 mysql 建表语句如下:

drop table abc,cdef;
CREATE TABLE abc (
    a VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'a',
    b VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'b',
    c VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'c'
    
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='abc';


CREATE TABLE cdef (
    c VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'c',
    d VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'd',
    e VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'e',
    f VARCHAR(20) NOT NULL DEFAULT '0' COMMENT 'f'  
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='cdef';




insert into abc (a,b,c) values 
('a1','b1','c1'),
('a1','b1','c1'),
('a5','b5','c5'),
('a2','b2','c2');
insert into cdef (c,d,e,f) values 
('c1','d1','e1','f1'),
('c3','d3','e3','f3'),
('c2','d2','e2','f2'),
('c2','d2','e2','f2');

  • 一。交叉连接:  没有where子句的交叉连接将产生连接表的笛卡尔积。 总条数等于 两表数据总数 之 积。
--笛卡尔交叉连接
select *
from abc ,cdef;

结果:

a1 b1 c1 c1 d1 e1 f1
a1 b1 c1 c1 d1 e1 f1
a5 b5 c5 c1 d1 e1 f1
a2 b2 c2 c1 d1 e1 f1
a1 b1 c1 c3 d3 e3 f3
a1 b1 c1 c3 d3 e3 f3
a5 b5 c5 c3 d3 e3 f3
a2 b2 c2 c3 d3 e3 f3
a1 b1 c1 c2 d2 e2 f2
a1 b1 c1 c2 d2 e2 f2
a5 b5 c5 c2 d2 e2 f2
a2 b2 c2 c2 d2 e2 f2
a1 b1 c1 c2 d2 e2 f2
a1 b1 c1 c2 d2 e2 f2
a5 b5 c5 c2 d2 e2 f2
a2 b2 c2 c2 d2 e2 f2


  • 二。内连接:内连接分为三种:自然连接、等值连接、非等值连接

a.自然连接:  在连接条件中使用等于=运算符比较被连接列的列值,但删除连接表中重复列

select *
from abc natural join cdef;

c1 a1 b1 d1 e1 f1
c1 a1 b1 d1 e1 f1
c2 a2 b2 d2 e2 f2
c2 a2 b2 d2 e2 f2

b.等值连接:利用on 或者 where 增加连接条件 等于=运算符比较被连接列的列值,不删除重复列

select a.*,d.*
from  abc a, cdef d
where a.c = d.c;
a1 b1 c1 c1 d1 e1 f1
a1 b1 c1 c1 d1 e1 f1
a2 b2 c2 c2 d2 e2 f2
a2 b2 c2 c2 d2 e2 f2

c.非等值连接:   在连接条件中,可以使用其他比较运算符,比较被连接列的列值,如:<、>、!=等

扫描二维码关注公众号,回复: 38517 查看本文章
select a.*,d.*
from  abc a, cdef d
where a.c != d.c;

结果:

a2 b2 c2 c1 d1 e1 f1
a1 b1 c1 c3 d3 e3 f3
a1 b1 c1 c3 d3 e3 f3
a5 b5 c5 c3 d3 e3 f3
a2 b2 c2 c3 d3 e3 f3
a1 b1 c1 c2 d2 e2 f2
a1 b1 c1 c2 d2 e2 f2
a5 b5 c5 c2 d2 e2 f2
a1 b1 c1 c2 d2 e2 f2
a1 b1 c1 c2 d2 e2 f2
a5 b5 c5 c2 d2 e2 f2

  • 三。外链接:包括 左连接,右连接

a.左连接:  左边为主,右边往左边连接,右边不存在对应的列 全为null

select a.*,d.*
from  abc a left join  cdef d on a.c = d.c;

结果:

a1 b1 c1 c1 d1 e1 f1
a1 b1 c1 c1 d1 e1 f1
a5 b5 c5 (null) (null) (null) (null)
a2 b2 c2 c2 d2 e2 f2
a2 b2 c2 c2 d2 e2 f2

b.右连接: 以右边为准,左边往右边连接,左边不存在对应的列全为null

select a.*,d.*
from  abc a right join  cdef d on a.c = d.c;

结果:

a1 b1 c1 c1 d1 e1 f1
a1 b1 c1 c1 d1 e1 f1
(null) (null) (null) c3 d3 e3 f3
a2 b2 c2 c2 d2 e2 f2
a2 b2 c2 c2 d2 e2 f2






 

猜你喜欢

转载自blog.csdn.net/u012425328/article/details/80032875