1、表格结构: 数据库中有三张表分别用于记录学生信息、课程信息和成绩信息。 数据表结构如下:
(1)学生表(student):学生 id 、学生姓名和性别
(2)课程表:课程 id 和课程名
(3)成绩表:成绩 id 、学生 id 、课程 id 和分数
问题:
a.查询学生选择的课程信息
SELECT a.sname,a.gender,a.cname FROM (SELECT student.sname,student.gender,mark.score,course.cname FROM student,mark,course WHERE student.sid = mark.sid AND course.cid = mark.cid) AS a ORDER BY sname;
2、表结构如下:
(1)department部门表
(2)employee员工表
(3)project项目表
(4)问题:
a.查询名为 “Tom” 的员工所在部门做了几个工程
注意:子查询只有在结果来自一个表时才有用
SELECT of_dpt,COUNT(proj_name) AS count_project FROM project GROUP BY of_dpt HAVING of_dpt IN (SELECT in_dpt FROM employee WHERE name='Tom');
b.查询不同员工的id和其所在部门的人数
注意:需要显示两个表或多个表中的数据,这时就必须使用连接 (join) 操作。 连接的基本思想是把两个或多个表当作一个新的表来操作
SELECT id,name,people_num FROM employee,department WHERE employee.in_dpt = department.dpt_name ORDER BY id;
等同于:
SELECT id,name,people_num FROM employee JOIN department ON employee.in_dpt = department.dpt_name ORDER BY id;
c.使用连接查询的方式,查询出各员工所在部门的人数与工程数,工程数命名为 count_project。(连接 3 个表,并使用 COUNT 内置函数)
SELECT name, people_num, COUNT(proj_name) AS count_project FROM employee, department, project WHERE in_dpt = dpt_name AND of_dpt = dpt_name GROUP BY name, people_num; +------+------------+---------------+ | name | people_num | count_project | +------+------------+---------------+ | Alex | 11 | 1 | | Jack | 12 | 2 | | Jim | 11 | 1 | | Jobs | 12 | 2 | | Joe | 12 | 2 | | Ken | 11 | 1 | | Mary | 12 | 2 | | Mike | 15 | 2 | | Rick | 10 | 1 | | Rose | 10 | 1 | | Tom | 15 | 2 | | Tony | 10 | 1 | +------+------------+---------------+ 12 rows in set (0.01 sec)