本文介绍: 在数据库中,连接(Join)是用于两个多个表中数据关联起来的操作连接操作有多种类型,其中包括内连接和外连接。内连接的话只有一种而外连接的话有六种,当然还有一种连接叫做交叉连接。

目录

下面以实例进行分析

内连接

inner join 或者join(等同于inner join)

外连接

left join 或者left outer join(等同于left join)

[ left join 或者left outer join(等同于left join) ] + [ where B.column is null ]


数据库中,连接(Join)是用于两个多个表中数据关联起来的操作。连接操作有多种类型,其中包括内连接和外连接。内连接的话只有一种而外连接的话有六种,当然还有一种连接叫做交叉连接。

#首先创建两张表ab
mysql> show create table aG
*************************** 1. row ***************************
       Table: a
Create Table: CREATE TABLE `a` (
  `id` int NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.01 sec)

mysql> show create table bG
*************************** 1. row ***************************
       Table: b
Create Table: CREATE TABLE `b` (
  `id` int NOT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
1 row in set (0.01 sec)
select *  from a join b on a.id=b.id;
or
select *  from a inner join b on a.id=b.id;
select * from a left join b on a.id=b.id;
or
select * from a left outer join b on a.id=b.id;

结果如下,TableA中B不存在记录填充Null

select * from a left outer join b on a.id=b.id where b.id is not null;

left join表a的数据全部显示匹配表b的数据也显示,而b.id再次过滤掉 表b的id为空

select * from a right outer join b on a.id=b.id;
or
select * from a right outer join b on a.id=b.id;

TableB中A不存在记录填充Null

select * from a right join b on a.id=b.id where a.id is not null;
 select * from a left join b on a.id=b.id union select * from a right join b on a.id=b.id;

union过后,重复记录合并(id为2,3,4的三条记录

select * from a left join b on a.id=b.id where b.id is null union select * from a right join b on a.id=b.id where a.id is null;
 select * from a cross join b;
select * from a cross join b where a.id=b.id;

注:隐式连接(Implicit Join)会出现数据冗余性能问题,主要是因为它使用逗号分隔表名方式进行连接,而没有明确指定连接条件,这样就会导致以下两个问题

  1. 数据冗余问题: 隐式连接会产生笛卡尔积,即将左表的每一行与右表的每一行进行组合然后返回所有可能组合结果,包括那些并不符合连接条件的组合。这就会导致结果集中出现多余的数据,从而产生数据冗余的问题。
  2. 性能问题: 隐式连接的查询效率很低,因为它会处理大量的无用数据,浪费系统资源时间。当表a和表b的记录数都很大时,隐式连接会产生庞大的临时表,消耗大量内存和CPU资源。此外,由于没有明确指定连接条件,数据库引擎会对每一个可能组合进行比较,这会进一步降低查询效率
explain select * from a join b on a.id=b.id;
  1. 从a表取出一行
  2. 取出的这一行取出字段1,然后到表b中查找a.id=b.id
  3. 取出从表b中获取到的数据,跟从表a中的数据组成一行,作为结果集的一部分
  1. A left join B 返回 A 表数据,附带 B 表中符合条件的数据
  2. A left join B right join C
  3. A left join B 假设等于结果 AB
  4. AB left join C 返回 AB ,附带 C中符合条件的数据
  1. A left join B 返回 A 表数据,附带 B 表中符合条件的数据
  2. A left join B right join C
  3. A left join B 假设等于结果 AB
  4. AB right join C 返回 C ,附带 AB 中符合条件的数据

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注