文章目录
- 0. 交集、并集、差集含义说明
- 1. 简单演示上图七种情况
- 0. A、B表数据准备
- 1. left outer join 简称 left join 左表所有数据,右表关联数据,没有的以null填充
- 2. right outer join 简称 right join,右表所有数据,左表关联数据,没有的以null填充
- 3. inner join 简称 join 交集
- 4. A left join B where B.key is null,A、B的差集是 A-B = 1
- 5. B right join where A.key is null,B、A的差集是 B-A = 4
- 6、7. full outer join 简写为full join(mysql不支持,oracle可以)
- 2. 笛卡尔积 A * B
- 1. 不带连接条件的笛卡尔积
- 2. 带连接条件的笛卡尔积变inner join
0. 交集、并集、差集含义说明
A 是1、2、3
B是2、3、4
A、B的交集是A∩B = 2、3
A、B的并集是 AUB = 1、2、3、4
A、B的差集是 A-B = 1
B、A的差集是 B-A = 4
1. 简单演示上图七种情况
0. A、B表数据准备
CREATE TABLE `xin_stu_t` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',`relation_id` bigint DEFAULT NULL COMMENT '外键, 记录教师id',`student_name` varchar(30) DEFAULT NULL COMMENT '姓名',`student_age` bigint DEFAULT NULL COMMENT '年龄',`school` varchar(300) DEFAULT NULL COMMENT '学校',PRIMARY KEY (`id`) USING BTREE,KEY `xin_s_relation_id` (`relation_id`),KEY `xin_s_student_name` (`student_name`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='学生表';CREATE TABLE `xin_teach_t` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',`teacher_name` varchar(30) DEFAULT NULL COMMENT '教师姓名',`teacher_age` bigint DEFAULT NULL COMMENT '教师年龄',`school` varchar(300) DEFAULT NULL COMMENT '学校',PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='教师表';INSERT INTO lelele.xin_stu_t (relation_id,student_name,student_age,school) VALUES(NULL,'尤仁义1',11,'徐州中学'),(1,'尤仁义2',12,'徐州中学'),(NULL,'朱有理1',11,'徐州中学'),(2,'朱有理2',12,'徐州中学'),(2,'朱有理3',13,'徐州中学'),(3,'宋昆明1',11,'徐州中学'),(3,'宋昆明2',12,'徐州中学'),(9,'宋昆明3',13,'徐州中学');INSERT INTO lelele.xin_teach_t (teacher_name,teacher_age,school) VALUES('王翠花1',31,'徐州中学'),('王翠花2',31,'徐州中学'),('王翠花3',33,'徐州中学'),('王翠花4',34,'徐州中学'),('王翠花5',35,'徐州中学');
1. left outer join 简称 left join 左表所有数据,右表关联数据,没有的以null填充
select A.*,B.* from xin_stu_t A left join xin_teach_t B on A.relation_id = B.id
select A.*,B.* from xin_stu_t A left outer join xin_teach_t B on A.relation_id = B.id
2. right outer join 简称 right join,右表所有数据,左表关联数据,没有的以null填充
select A.*,B.* from xin_stu_t A right join xin_teach_t B on A.relation_id = B.id
select A.*,B.* from xin_stu_t A right outer join xin_teach_t B on A.relation_id = B.id
3. inner join 简称 join 交集
select A.*,B.* from xin_stu_t A inner join xin_teach_t B on A.relation_id = B.id
select A.*,B.* from xin_stu_t A join xin_teach_t B on A.relation_id = B.id
4. A left join B where B.key is null,A、B的差集是 A-B = 1
select A.*,B.* from xin_stu_t A left join xin_teach_t B on A.relation_id = B.id where B.id is null
5. B right join where A.key is null,B、A的差集是 B-A = 4
select A.*,B.* from xin_stu_t A right join xin_teach_t B on A.relation_id = B.id where A.id is null
6、7. full outer join 简写为full join(mysql不支持,oracle可以)
2. 笛卡尔积 A * B
1. 不带连接条件的笛卡尔积
select A.*,B.* from xin_stu_t A, xin_teach_t B
2. 带连接条件的笛卡尔积变inner join
select A.*,B.* from xin_stu_t A, xin_teach_t B where A.relation_id = B.id