mysql处理部门、用户信息 多级部门关联问题
描述: 现有两张表 dep部门表 emp用户表
使用sql查询出用户 一级部门名称 二级部门名称
dep 部门表如下
emp表如下
数据库语句如下:
DROP TABLE IF EXISTS `dep`;
CREATE TABLE `dep` (
`id` tinyint(10) DEFAULT NULL,
`supid` tinyint(10) DEFAULT '0',
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of dep
-- ----------------------------
INSERT INTO `dep` VALUES ('10', '0', '生物信息研究院');
INSERT INTO `dep` VALUES ('11', '10', '健康大数据部');
INSERT INTO `dep` VALUES ('20', '0', '工程院');
INSERT INTO `dep` VALUES ('21', '20', '技术部');
INSERT INTO `dep` VALUES ('22', '20', '市场部');
INSERT INTO `dep` VALUES ('30', '0', '招商部');
-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
`id` tinyint(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`depId` tinyint(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES ('1', '杨国辉', '11');
INSERT INTO `emp` VALUES ('2', '李四', '21');
INSERT INTO `emp` VALUES ('3', '王五', '22');
INSERT INTO `emp` VALUES ('4', '立恒', '21');
INSERT INTO `emp` VALUES ('5', '提提', '30');
INSERT INTO `emp` VALUES ('6', '微微', '10');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`ctime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'lili', '2017-06-08 16:29:33');
INSERT INTO `user` VALUES ('2', 'zhangzhan', '2017-06-07 16:29:41');
INSERT INTO `user` VALUES ('3', 'lisi', '2017-06-08 16:29:45');
INSERT INTO `user` VALUES ('4', 'lisi', '2017-06-08 16:29:57');
问题:dep部门表包含一级部门以及二级部门,之间关系以supid和id关联
emp用户表 depId 是dep表的外键
emp表中用户:1. 关联二级部门 二级部门的depid
2. 直接关联一级部门 一级部门的depid
解决问题的两种sql:
1. SELECT e.name,IF (d.supid =0,NULL,d.name) AS sconddep,IF(d.supid = 0,d.name,(SELECT NAME FROM dep WHERE id = d.supid)) AS firstdep FROM emp e,dep d WHERE e.depId = d.id
使用if语句
2. SELECT e.name,d2.name AS firstdep,d3.name AS seconddep FROM emp e JOIN dep d1 ON e.depId = d1.id LEFT JOIN dep d2 ON d2.id = d1.supid OR (d2.id = e.depId AND d2.supid =0) LEFT JOIN dep d3 ON d3.id = d1.id and d3.supid >0
使用左关联 dep2作为一级部门表 (注:一级部门表两种情况 ① 作为部门直接关联用户 ② 作为二级部门的上级部门) dep3作为二级部门表
结果: