集合操作 举个例子,要获取所有拥有 gmail 或者 hotmail 邮箱账号的学生信息: (SELECT * FROM Student WHERE Email like '%@gmail.com') UNION (SELECT * FROM Student WHERE Email like '%@hotmail.com');
但以下语句无法正常工作,因为所作用的两个表的属性不同: (SELECT StudentID, Name FROM Student) UNION (SELECT Email FROM Student);
连接操作 JOIN
内连接(INNER JOIN) 内连接可以进一步被分为:相等连接、自然连接、交叉连接
交叉连接 (CROSS JOIN) 如果 A 和 B 是两个集合,那么它们的交叉连接就记为:A x B。比如: SELECT * FROM employee CROSS JOIN department; -- 隐式表达交叉连接 SELECT * FROM employee, department;
相等连接(equi-join,或 equijoin) SELECT DISTINCT c.Cname FROM Course c INNER JOIN Enrol e ON c.No=e.CourseNo;
自然连接(NATURAL JOIN) SELECT * FROM Student s NATURAL JOIN Enrol1 e;
外连接(OUTER JOIN) 外连接可依据连接表保留左表,右表或全部表的行而进一步分为左外连接,右外连接和全连接。 需要注意一点,当外部连接既包含 ON 子句又包含 WHERE 子句时,应当只把表之间的连接条件写在 ON 子句中,对表中数据的筛选必须写在 WHERE 子句中。而内部连接的各条件表达式既可以放在 ON 子句又可以放在 WHERE 子句中。这是因为对于外部连接,保留表中被 ON 子句筛除掉的行要被添加回来,在此操作之后才会用 WHERE 子句去筛选连接结果中的各行。
左外连接(LEFT OUTER JOIN) SELECT * FROM Student s LEFT JOIN Enrol1 e ON s.StudentID=e.StudentID;
右外连接(RIGHT OUTER JOIN) 右连接操作返回右表的所有行和这些行在左表中匹配的行(没有匹配的,来源于左表的列值设为 NULL)。 SELECT * FROM Student s RIGHT JOIN Enrol1 e ON s.StudentID=e.StudentID;
子查询 Subqueries
SELECT s.*, e1.CourseNo FROM Student s NATURAL JOIN Enrol e1 WHERE e1.CourseNo IN (SELECT e2.CourseNo FROM Enrol e2 GROUP BY e2.CourseNo HAVING COUNT(*) < 10);
列出所有至少参加一门课程的学生信息: SELECT s.* FROM Student s WHERE EXISTS (SELECT * FROM Enrol e WHERE s.StudentID=e.StudentID);
列出所有没有参加任何课程的学生信息: SELECT s.* FROM Student s WHERE NOT EXISTS (SELECT * FROM Enrol e WHERE s.StudentID=e.StudentID);
列出在2016学年第二学期中,报名学生人数最多的课程: SELECT e.CourseNo FROM (SELECT e1.CourseNo, COUNT(*) AS NoOfStudents FROM Enrol e1 WHERE e1.Semester = '2016 S2' GROUP BY e1.CourseNo) e WHERE e.NoOfStudents = (SELECT MAX(e2.NoOfStudents) FROM (SELECT e1.CourseNo, COUNT(*) AS NoOfStudents FROM Enrol e1 WHERE e1.Semester = '2016 S2' GROUP BY e1.CourseNo) e2);
列出在2016学年第二学期中,报名学生人数比至少一个其他课程要多的课程: SELECT e.CourseNo FROM (SELECT e1.CourseNo, COUNT(*) AS NoOfStudents FROM Enrol e1 WHERE e1.Semester = '2016 S2' GROUP BY e1.CourseNo) e WHERE e.NoOfStudents > ANY (SELECT e2.NoOfStudents FROM (SELECT e1.CourseNo, COUNT(*) AS NoOfStudents FROM Enrol e1 WHERE e1.Semester = '2016 S2' GROUP BY e1.CourseNo) e2);
具体创建数据库的代码可以通过下面的链接得到: https://github.com/OddUlrich/Experiment-Code/tree/master/SQL%20Select%20Practice 若想做更多关于查询的练习,可以访问下面的这个网站: https:///
参考资料:
|
|