SQL语法——多表联合查询

时间:2022-08-18 00:25:45
/*
多表联合查询
*/


/* -- 1. 简单的多表联合

SELECT 列名 [[,列名]...]
FROM 表名1,表名2,...
WHERE 检索条件;
*/


-- e.g.

-- “001” 号课成绩由高到低顺序显示所有学生的姓名

SELECT sname FROM student,sc
WHERE student.s# = sc.s# AND sc.c# = '001'
ORDER BY score DESC;




-- 有薪水差额的任意两位老师

SELECT t1.tname AS tt1,t2.tname AS tt2
FROM teacher t1,teacher t2
WHERE t1.salary > t2.salary;



/* -- 2. 并-交-差 的处理
并 UNION [ALL]
交 INTERSECT [ALL]
差 EXCEPT [ALL]

不带ALL:自动删除重复的元组
含有ALL:保留重复的元组

-- 子查询 {UNION [ALL] | INTERSECT [ALL] | EXCEPT [ALL] 子查询}

子查询1的一个元组出现m次,子查询2的一个元组出现n次
含有ALL时,元组出现的次数:
子查询1 UNION ALL 子查询2 -- m + n 次
子查询1 INTERSECT ALL 子查询2 -- MIN(m,n) 次
子查询1 EXCEPT ALL 子查询2 -- MAX(0,m-n) 次
*/

-- e.g.
-- 求学过002号课或003号课的同学的学号
SELECT s# FROM sc WHERE c# = '002'
UNION
SELECT s# FROM sc WHERE c# = '003';


-- 或
SELECT s# FROM sc WHERE c# = '002' OR c# = '003';


-- 求学过002号课又学过003号课的同学的学号
SELECT s# FROM sc WHERE c# = '002'
INTERSECT
SELECT s# FROM sc WHERE c# = '003';


-- 或
SELECT s# FROM sc WHERE c# = '002'
IN (SELECT s# FROM sc WHERE c# = '003');


-- 求没学过002号课的同学的学号
SELECT DISTINCT s# FROM sc
EXCEPT
SELECT s# FROM sc WHERE c# = '002';


-- 或
SELECT DISTINCT s# FROM sc sc1
WHERE NOT EXISTS
(SELECT * FROM SC WHERE C# = '002' AND S# = sc1.s#);




/*--3. 内连接和外连接

SELECT 列名 [ [,列名]... ]
FROM 表名1
[NATURAL] [INNER | {LEFT | RIGHT | FULL} [OUTER]] JOIN 表名2
{ON 连接条件 | USING (colname {,colname...})}
[WHERE 检索条件]...;

连接类型(4选1):
INNER JOIN
LEFT [OUTER] JOIN
RIGHT [OUTER] JOIN
FULL [OUTER] JOIN

连接条件(3选1):
NATURAL
ON<连接条件>
USING (col1,col2,..,coln)

*/