多表查询
– 1. 查询员⼯的姓名及其所在部⻔的名字和城市
select ename,dname,loc
from emp,dept
where emp.deptno = dept.deptno;
– 2. 查询员⼯的姓名和他的管理者的姓名
select e1.ename,e2.ename
from emp e1,emp e2
where e1.mgr = e2.empno;
– 3. 查询员⼯的编号、姓名、部⻔编码、部⻔名称以及部⻔所在城市。要求:把没有部⻔的员⼯也查出来
select empno,ename,emp.deptno,dname,loc
from dept,emp
where emp.deptno = dept.deptno;
– 4. 查询员⼯的信息及其所在部⻔的信息。要求:把没有员⼯的部⻔也查出来
select emp.*,dept.*
from dept left join emp
on emp.deptno = dept.deptno;
– 5. 查询员⼯的信息及其所在部⻔的信息。要求:只查询没有员⼯的部⻔
select emp.*,dept.*
from dept left join emp
on emp.deptno = dept.deptno
where ename is null;
– 6. 查询并显示SALES部⻔的职位
select distinct job
from dept,emp
where emp.deptno = dept.deptno
and dname = 'sales';
– 7. 查询所有部⻔的名称、所在地、员⼯数量以及平均⼯资
select dname,loc,count(*),avg(sal)
from dept,emp
where emp.deptno = dept.deptno
group by dept.deptno;
– 8. 执⾏下⾯两条查询语句,并⽐较查询结果
select e1.ename, e2.ename
from emp e1, emp e2
where e1.mgr = e2.empno;
select e1.ename, e2.ename
from emp e1, emp e2
where e1.empno = e2.mgr;
-- 显示顺序不同
– 9. 假设员⼯表中,员⼯和管理者中间只有⼀个层级,也就是说,每个员⼯最多只有⼀个上级,作为管理者的员⼯不再有上级管理者,并且,上级管理者相同的员⼯,他们属于同⼀个部⻔。找出EMP中那些⼯资⾼于他们所在部⻔的管理者⼯资的员⼯。
select e1.ename
from emp e1,emp e2
where e1.mgr = e2.empno
and e1.sal > e2.sal;
– 10. 有USERLIST表如图所示:
有CHAEGE表如图所示:
请⽤最少的SQL语句,产⽣如下表所示的查询结果:
其中,数据是经过USERLIST、CHAEGE表进⾏合适的连接,并以ACCOUNT字段为关键字分组求和得
到。
特别注意:电话号码421004在USERLIST表中有⼀条记录,在CHAEGE表中并没有纪录。但是,在查
询结果中,合同CCCC具有⼀条记录。
select account,count(account) users,sunm(rent) rent,sum(fee01) fee01,sum(fee02) fee02,sum(fee03) fee03,sum(fee04) fee04
from userlist u left join chaege c
on u.telephone = c.telephone
group by account;
– 11.有学员表student,⽤于记录学员、姓名下、性别、年龄、组织部⻔;有课程表course,⽤于记录课程编号、课程名称;还有选课表sc,⽤于记录学号、课程编号、成绩。三表的结构以及关联如图所示:
完成如下要求的SQL语句:
-
查询选修了“计算机原理”的学⽣学号和姓名
-
查询“周星驰”同学选修了的课程名字
select student.Sno,sname from student,sc,course where student.sno = sc.no and sc.cno = course.cno and cname = '计算机原理'; select cname from student,sc,course where student.sno = sc.no and sc.cno = course.cno and sname = '周星驰';
– 12.有表test,结构如下:
编写SQL语句,查询所有年龄⽐所属主管年龄⼤的⼈的ID和NAME。
select t1.name,t1.id
from test t1,test t2
where t1.manager = t2.id
and t1.age > t2.age;
– 13。有表city记录城市信息。
有表state,记录省份信息。
想要得到下表所示查询结果:
编写相应的SQL语句。
select cityno ,cityname,c.stateno,statename
from city c left outer join state s
on c.stateno = s.stateno;