sql 多表查询
------
笛卡尔积:tableA * tableB
select * from emp,dept
一、92 标准的多表查询
(1)等值查询
两张表是平级关系
1、等值查询
SELECT EMPNO,ENAME,DNAME
FROM EMP,DEPT
WHERE ENAME = 'SMITH'
AND EMP.DEPTNO = DEPT.DEPTNO;2、非等值查询
SELECT E.EMPNO,E.ENAME,E.SAL,S.LOSAL,S.HISAL ,S.GRADE
FROM EMP E,SALGRADE S
WHERE E.ENAME = 'SMITH'
AND E.SAL >=S.LOSAL
AND E.SAL <=S.HISAL;
(2)外连查询
主次表关系
1、左外连接
SELECT E.EMPNO,E.ENAME,D.DNAME,D.DEPTNO
FROM EMP E,DEPT D
WHERE E.DEPTNO = D.DEPTNO(+);
2、右外连接
SELECT E.EMPNO,E.ENAME,D.DNAME,D.DEPTNO
FROM EMP E,DEPT D
WHERE E.DEPTNO(+) = D.DEPTNO;
备注:当条件过多时,连接条件多,过滤条件多,就容易造成混淆
二、99 标准的多表查询
(1)交叉连接 CROSS JOIN
SELECT * FROM EMP,DEPT; --92标准
SELECT * FROM EMP CROSS JOIN DEPT; --99标准
(2)自然连接 NATURAL JOIN 类似等值连接
SELECT E.EMPNO,E.ENAME,D.DNAME
FROM EMP E, DEPT D
WHERE E.DEPTNO = D.DEPTNO; --92不指定连接的列的话
SELECT E.EMPNO,E.ENAME,D.DNAME,DEPTNO
FROM EMP E NATURAL JOIN DEPT D
WHERE DEPTNO =10; --99
(3)内链查询 inner join inner 可以省去
内连接分为等值连接和不等连接两种
select * from T_student s,T_class c where s.classId = c.classId 等于 select * from T_student s inner join T_class c on s.classId = c.classId
select * from T_student s inner join T_class c on s.classId <> c.classId
(4)using子句 :当项链的表中出现很多同名列,自然连接将无法满足要求,可以在连接时使用using子句来设置用于等值连接列名
SELECT E.EMPNO,E.ENAME,D.DNAME,DEPTNO
FROM EMP E NATURAL JOIN DEPT D
USING (DEPTNO)
WHERE DEPTNO =10;--USING来制定要使用哪一个同名列进行连接
(5)on 子句 是生成临时表时使用的条件 where 是对临时表的过滤(on and 和 on where 都会对生成的临时表进行过滤)
SELECT E.EMPNO,E.ENAME,D.DNAME FROM EMP E join DEPT D ON E.DEPTNO = D.DEPTNO
SELECT E.EMPNO,E.ENAME,D.DNAME FROM EMP E join DEPT D ON E.DEPTNO = D.DEPTNO
AND E.EMPNO = 7788SELECT E.EMPNO,E.ENAME,D.DNAME FROM EMP E join DEPT D ON E.DEPTNO = D.DEPTNO
WHERE E.EMPNO = 7788
(6)外连接
1、左外连接 left join
SELECT E.EMPNO,E.ENAME,D.DNAME,D.DEPTNO
FROM EMP E left join DEPT D
ON E.DEPTNO = D.DEPTNO;
2、右外连接 right join
SELECT E.EMPNO,E.ENAME,D.DNAME,D.DEPTNO
FROM EMP E RIGHT join DEPT D
ON E.DEPTNO = D.DEPTNO(+);
3、交叉连接 FULL join
SELECT E.EMPNO,E.ENAME,D.DNAME,D.DEPTNO
FROM EMP E FULL join DEPT D
ON E.DEPTNO = D.DEPTNO(+);
------