为了减少对数据库的查询次数,例如在互不关联的表中为了减轻系统的压力,我们可以通过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
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联表查询的特点是什么的详细内容。更多信息请关注PHP中文网其他相关文章!