前言为了减少对数据库的查询次数,例如在互不关联的表中为了减轻系统的压力,我们可以通过union all关键词将多个表查到的数据做一个联查处理
(便于统计分析时使用到不同的数据而只用一次请求)
举例:通过一条sql语句一次查询查询学生表中的性别为男的学生总数和教师表中的教师性别为男的教师总数
数据库表准备:
1、student表
set names utf8mb4;set foreign_key_checks = 0;-- ------------------------------ table structure for student-- ----------------------------drop table if exists `student`;create table `student` ( `id` varchar(20) character set utf8mb4 collate utf8mb4_0900_ai_ci not null, `name` varchar(20) character set utf8mb4 collate utf8mb4_0900_ai_ci not null default '', `birth` varchar(20) character set utf8mb4 collate utf8mb4_0900_ai_ci not null default '', `sex` varchar(10) character set utf8mb4 collate utf8mb4_0900_ai_ci not null default '', primary key (`id`) using btree) engine = innodb character set = utf8mb4 collate = utf8mb4_0900_ai_ci row_format = dynamic;-- ------------------------------ records of student-- ----------------------------insert into `student` values ('01', '赵雷', '1990-01-01', '男');insert into `student` values ('02', '钱电', '1990-12-21', '男');insert into `student` values ('03', '孙风', '1990-05-20', '男');insert into `student` values ('04', '李云', '1990-08-06', '男');insert into `student` values ('05', '周梅', '1991-12-01', '女');insert into `student` values ('06', '吴兰', '1992-03-01', '女');insert into `student` values ('07', '郑竹', '1989-07-01', '女');insert into `student` values ('08', '王菊', '1990-01-20', '女');set foreign_key_checks = 1;
2、teacher表
set names utf8mb4;set foreign_key_checks = 0;-- ------------------------------ table structure for teacher-- ----------------------------drop table if exists `teacher`;create table `teacher` ( `id` varchar(20) character set utf8mb4 collate utf8mb4_0900_ai_ci not null, `name` varchar(20) character set utf8mb4 collate utf8mb4_0900_ai_ci not null default '', `sex` varchar(255) character set utf8mb4 collate utf8mb4_0900_ai_ci null default null, primary key (`id`) using btree) engine = innodb character set = utf8mb4 collate = utf8mb4_0900_ai_ci row_format = dynamic;-- ------------------------------ records of teacher-- ----------------------------insert into `teacher` values ('01', '张三', '男');insert into `teacher` values ('02', '李四', '女');insert into `teacher` values ('03', '王五', '男');set foreign_key_checks = 1;
一、传统方法(查询性能不佳)对所查询的数据封装成一个表,在分别对表的数据查询展示出来。
这种方法比较简单但是会对数据库的查询次数大大提高
select t1.学生男生总数, t2.男教师总数 from ( select count( id ) as 学生男生总数 from student where student.sex = '男' ) t1, ( select count( id ) as 男教师总数 from teacher where teacher.sex = '男' ) t2
二、使用union all将多个表联合成一个表查询 select t.* from ( select count(id) as a,0 as b from student where student.sex = '男' union all select 0 as a,count(id) as b from teacher where teacher.sex = '男' ) t
1、此时a代表学生性别为男生的总人数,b代表教师性别为男的总人数
2、此时我们只需对a和b分别求和,就能够查询出男学生和男教师的总人数
select sum(t.a) as 学生男生总数,sum(t.b) as 男教师总数 from ( select count(id) as a,0 as b from student where student.sex = '男' union all select 0 as a,count(id) as b from teacher where teacher.sex = '男' ) t
以上就是mysql联表查询的特点是什么的详细内容。