首先两表如下所示
两表结构如下
查询要求
1 所有有门派的人员信息
select *from t_emp right join t_dept on t_emp.deptId=t_dept.id;
2 列出所有用户,并显示其机构信息
select t_emp.name,t_dept.id,t_dept.deptName,t_dept.address,t_dept.CEO from t_emp left join t_dept on t_emp.deptId=t_dept.id;
3 列出不入派的人员:
select name from t_emp left join t_dept on t_emp.deptId=t_dept.id where t_emp.deptIdis null;
4 所有没人入的门派 :
select deptName from t_emp right join t_dept on t_emp.deptId=t_dept.id where t_emp.deptId is null;
5 列出所有人员和门派的对照关系
SELECT * FROM t_emp A LEFT JOIN t_dept B ON A.deptId = B.id UNION SELECT * FROM t_emp A RIGHT JOIN t_dept B ON A.deptId = B.id;
6 列出所有没入派的人员和没人入的门派
select * from t_emp left join t_dept on t_emp.deptId=t_dept.id where t_emp.deptId isnull union select * from t_emp right join t_dept on t_emp.deptId=t_dept.id where t_emp.deptIdd is null;
7 求各个门派对应的掌门人名称:
select de.deptName,emp.name from t_dept as de inner join t_emp as emp on de.CEO=emp.id;
d;
8 求所有当上掌门人的平均年龄:
select avg(emp.age) from t_dept as de inner join t_emp as emp on de.CEO=emp.id;
或者
select avg(age) from (select emp.name,emp.age from t_dept as de inner join t_emp as emp on de.CEO=emp.id) as age;
9 求所有人物对应的掌门名称:
select emp.name,zm.name from t_emp as emp left join (SELECT t_emp.name,t_emp.deptId as id from t_dept left JOIN t_emp on t_emp.id = t_dept.CEO) as zm on zm.id=emp.deptId;
10 列出自己的掌门比自己年龄小的人员
SELECT a.`name`,a.`age`,c.`name` ceoname,c.`age` ceoage FROM t_emp a LEFT JOIN t_dept b ON a.`deptId`= b.`id` LEFT JOIN t_emp c ON b.`CEO`= c.`id` WHERE c.`age`<a.`age`;
11 列出所有年龄低于自己门派平均年龄的人员
select c.name,c.age,d.avg_age from t_emp as c inner join (select deptId,avg(age) as avg_age from t_emp where deptId is not null group by(deptId)) as d on c.deptId=d.deptId where c.age<d.avg_age;
12 列出至少有2个年龄大于40岁的成员的门派
select de.deptName,count(*) from t_emp as em inner join t_dept as de on em.deptId=de.id where age>40 group by de.deptName,de.id having count(*)>=2;
13 至少有2位非掌门人成员的门派
SELECT c.deptname, c.id,COUNT(*) FROM t_emp a INNER JOIN t_dept c ON a.`deptId` =c.`id` LEFT JOIN t_dept b ON a.`id`=b.`ceo` WHERE b.`id` IS NULL GROUP BY c.`id` ,c.deptname HAVING COUNT(*)>=2;
14 列出全部人员,并增加一列备注“是否为掌门”,如果是掌门人显示是,不是掌门人显示否
select emp.name,CASE WHEN de.`id` is null THEN '否' ELSE '是' END '是否为掌门' from t__emp as emp left join t_dept as de on emp.id=de.CEO;
15 列出全部门派,并增加一列备注“老鸟or菜鸟”,若门派的平均值年龄>50显示“老鸟”,否则显示“菜鸟”
select de.deptName,if (avg(emp.age)>50,'老鸟','菜鸟') as '老鸟or菜鸟' from t_emp as emp inner join t_dept as de on emp.deptId=de.id group by de.id;
16 显示每个门派年龄最大的人
select name,age from t_emp as emp inner join (select deptId,max(age) maxage from t_emp where deptid is not null group by deptid) as dm on emp.age=dm.maxage and emp.deptid=dm.deptid;