mysql各种join连接查询
最近项目用到了几次sql join查询 来满足银行变态的需求;正好晚上自学时,看到了相关视频,所以记录下相关知识,下次再用时,根据如下图片,便可知道 怎么写sql;
注意点: 在join操作中的 on ... where ... 应该放哪些条件;目前理解 on 后放2表关联部分;where后放最终数据筛选部分;
1.下图为各种join操作的图表解释及sql语句
2.自测
- 建表:分别为 分数表(sc),及学生表(student);关系为 student.student_id=sc.id ;语句如下:
-
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for sc -- ---------------------------- DROP TABLE IF EXISTS `sc`; CREATE TABLE `sc` ( `id` int(11) NOT NULL, `score` int(255) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact; -- ---------------------------- -- Records of sc -- ---------------------------- INSERT INTO `sc` VALUES (10, 40); INSERT INTO `sc` VALUES (11, 20); INSERT INTO `sc` VALUES (12, 30); SET FOREIGN_KEY_CHECKS = 1;
-
DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL, `student_id` int(11) NULL DEFAULT NULL, `name` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES (0, 12, 'b'); INSERT INTO `student` VALUES (1, 11, 'a'); INSERT INTO `student` VALUES (3, 13, 'c'); SET FOREIGN_KEY_CHECKS = 1;
-
- 建表数据结果如下:
-
可以根据图表中的sql 语句进行相关join查询测试;
3.简单测试2个结果:
测试第一个join 语句如下:
select student.student_id,sc.score from student LEFT JOIN sc on student.student_id=sc.id
结果为:
测试第二个join 语句如下:
select student.student_id,sc.score from student LEFT JOIN sc on student.student_id=sc.id WHERE sc.id is null
结果为:;解析:在 第一个语句的基础上加上 WHERE sc.id is null ;只保留sc.id 为 nul的数据,而这个数据 只有 student 和 sc 非交集部分才有;
重点为 mysql 没有 full outer join 或者 full join;导致 要想完成 图中的 6,7部分,必须使用 图中1和4 或 1和5 的 union 来实现;
测试第6个join 语句如下:
select student.student_id,sc.score from student left JOIN sc on student.student_id=sc.id UNION select student.student_id,sc.score from student RIGHT JOIN sc on student.student_id=sc.id
结果为:
测试第7个join 语句如下:
select student.student_id,sc.score from student left JOIN sc on student.student_id=sc.id WHERE sc.id is null UNION select student.student_id,sc.score from student RIGHT JOIN sc on student.student_id=sc.id WHERE student.student_id is null
结果为: