sql 查询 不满足 (一个教师编号 的角色 (role ='2'or(role='1'and role ='0')) )
准备 一个 teacher 表 和数据
表 teacher 和数据
c
-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`role` int(11) NULL DEFAULT NULL COMMENT '(角色;0:普通教师 1:班主任教师,2:普通教师 + 班主任)',
`teacher_no` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '教师编号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, 0, 'T001');
INSERT INTO `teacher` VALUES (2, 1, 'T001');
INSERT INTO `teacher` VALUES (3, 2, 'T002');
INSERT INTO `teacher` VALUES (4, 0, 'T003');
INSERT INTO `teacher` VALUES (5, 1, 'T004');
INSERT INTO `teacher` VALUES (6, 0, 'T005');
INSERT INTO `teacher` VALUES (7, 1, 'T006');
SET FOREIGN_KEY_CHECKS = 1;
teacher 表 正确数据 截图
根据sql 查出来 不正确数据
sql
c
SELECT DISTINCT t1.teacher_no
FROM (
SELECT teacher_no,
MAX(CASE WHEN Role = '0' THEN 1 ELSE 0 END) AS role_ZERO_count,
MAX(CASE WHEN Role = '1' THEN 1 ELSE 0 END) AS role_One_count,
MAX(CASE WHEN Role = '2' THEN 1 ELSE 0 END) AS role_Two_flag
FROM teacher
GROUP BY teacher_no
) t2
JOIN teacher t1
ON t1.teacher_no = t2.teacher_no
WHERE NOT(t2.role_Two_flag = 1 OR (t2.role_ZERO_count = 1 AND t2.role_One_count = 1))