一、合并结果集
- 要求被合并的表中,列的类型和列数相同
- UNION,去除重复行
- UNION ALL,不去除重复行
SELECT * FROM ab
UNION (ALL)
SELECT * FROM cd;
二、内连接查询(方言)
方言语法:SELECT * FROM 表1 别名1, 表2 别名2 WHERE 别名1.xx=别名2.xx
例1:SELECT * FROM emp,dept
WHERE emp.deptno = dept.deptno;
例2:select emp.ename,emp.sal,dept.dname from emp, dept
WHERE emp.deptno = dept.deptno;
三、内连接查询(标准和自然)
标准语法:SELECT * FROM 表1 别名1 INNER JOIN 表2 别名2
ON 别名1.xx=别名2.xx
例:SELECT e.ename,e.sal,d.dname
FROM emp e INNER JOIN dept d
ON e.deptno = d.deptno;
自然语法:SELECT * FROM 表1 别名1 NATURAL JOIN 表2 别名2
自然语法的缺点:可读性降低,因为内部自动加WHERE条件,去除不想要的行。
四、外连接之左外连接
左外连接语法:SELECT * FROM 表1 别名1 LEFT OUTER JOIN 表2 别名2 ON 别名1.xx=别名2.xx
左外自然连接语法:SELECT * FROM 表1 别名1 NATURAL LEFT OUTER JOIN 表2 别名2 ON 别名1.xx=别名2.xx
左表记录无论是否满足条件都会查询出来,而右表只有满足条件才能出来。左表中不满足条件的记录,右表部分都为NULL
SELECT e.ename,e.sal,d.dname,e.deptno,d.deptno FROM
emp
e LEFT OUTER JOIN dept
d
ON e.deptno = d.deptno;
SELECT e.ename,e.sal,d.dname FROM
emp e NATURAL LEFT OUTER JOIN dept d;
五、外连接之右外连接
右外连接语法:SELECT * FROM 表1 别名1 RIGHT OUTER JOIN 表2 别名2 ON 别名1.xx=别名2.xx
右外自然连接语法:SELECT * FROM 表1 别名1 NATURAL RIGHT OUTER JOIN 表2 别名2 ON 别名1.xx=别名2.xx
右表记录无论是否满足条件都会查询出来,而左表只有满足条件才能出来。右表不满足条件的记录,其左表部分都为NULL
SELECT e.ename,e.sal,d.dname FROM
emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno;
SELECT e.ename,e.sal,d.dname FROM
emp e NATURAL RIGHT OUTER JOIN dept d;
六、外连接之全外连接
全外链接:可以使用UNION合并左外连接与右外连接的结果集来完成。
SELECT e.ename,e.sal,d.dname,e.deptno,d.deptno FROM
emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno
UNION
SELECT e.ename,e.sal,d.dname,e.deptno,d.deptno FROM
emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno;
SELECT e.ename,e.sal,d.dname FROM
emp e NATURAL LEFT OUTER JOIN dept d
UNION
SELECT e.ename,e.sal,d.dname FROM
emp e NATURAL RIGHT OUTER JOIN dept d;
七、子查询
SELECT * FROM emp WHERE sal = (SELECT MAX(sal) FROM emp);
SELECT * FROM emp WHERE sal > (SELECT AVG(sal) FROM emp);
SELECT * FROM emp WHERE sal > ALL (SELECT sal FROM emp WHERE job = ‘文员’);
SELECT * FROM emp WHERE sal > ANY (SELECT sal FROM emp WHERE job = ‘经理’);
SELECT * FROM emp WHERE (job,deptno,sal) IN ( SELECT job,deptno,sal FROM emp WHERE ename=‘殷天正’);