前置 sql 语句
用来创建表、插入数据
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
`id` int(11) NOT NULL COMMENT ‘员工编号‘,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘员工姓名‘,
`dept_id` int(11) NULL DEFAULT NULL COMMENT ‘部门编号‘,
`leader` int(11) NULL DEFAULT NULL COMMENT ‘直属领导id‘,
`is_enable` int(11) NULL DEFAULT NULL COMMENT ‘是否在职 1在职 0离职‘,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
INSERT INTO `emp` VALUES (1, ‘张三丰‘, 1, 0, 1);
INSERT INTO `emp` VALUES (2, ‘张无忌‘, 1, 1, 1);
INSERT INTO `emp` VALUES (3, ‘小龙女‘, 1, 1, 1);
INSERT INTO `emp` VALUES (4, ‘小白菜‘, 1, 3, 1);
INSERT INTO `emp` VALUES (5, ‘韦小宝‘, 2, 0, 1);
INSERT INTO `emp` VALUES (6, ‘令狐冲‘, 2, 0, 1);
INSERT INTO `emp` VALUES (7, ‘东方不败‘, 0, 8, 1);
INSERT INTO `emp` VALUES (8, ‘任我行‘, 3, 0, 1);
INSERT INTO `emp` VALUES (9, ‘李寻欢‘, 0, 8, 1);
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
`id` int(11) NOT NULL COMMENT ‘部门id‘,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘部门名称‘,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
INSERT INTO `dept` VALUES (1, ‘销售部‘);
INSERT INTO `dept` VALUES (2, ‘信息技术部‘);
INSERT INTO `dept` VALUES (3, ‘财务部‘);
INSERT INTO `dept` VALUES (4, ‘有关部门‘);
题目列表
1、查询张姓员工的员工信息和所在部门信息。
2、查询张三丰管理了几个员工
3、查询出所有实习员工(实习员工无部门信息)
4、查询每个部门有多少个员工,并打印部门名字、部门里的所有员工名字
-- 1、查询张姓员工的员工信息和所在部门信息。
SELECT t.Username FROM
(SELECT emp.id as id,emp.`name` as Username,emp.dept_id,emp.leader,emp.is_enable,dp.`name` FROM emp INNER JOIN dept dp
on emp.dept_id = dp.id WHERE emp.`name` LIKE ‘%张%‘) t
-- 2、查询张三丰管理了几个员工
SELECT count(*) FROM
(SELECT e2.name as e2name FROM emp e1 INNER JOIN emp e2 on
e1. id = e2.leader where e1.`name` = "张三丰") t;
-- 3、查询出所有实习员工(实习员工无部门信息)
SELECT count(*) from
(SELECT * from emp e1 where e1.dept_id not in (SELECT id from dept)) t
-- 4、查询每个部门有多少个员工,并打印部门名字、部门里的所有员工名字//group_concat用于拼接字符串,常与groupby在一起
SELECT * FROM
(SELECT group_concat(e1.name) as username,dp.name as clname ,count(e1.name) from emp e1 RIGHT JOIN dept dp on
e1.dept_id=dp.id GROUP BY dp.id) t