CASE表达式中的标量子查询
查找部门号为1800的部门ID,地点显示为CANADA,其他显示为USA
SELECT EMPLOYEE_ID,LAST_NAME,DEPARTMENT_ID,
(CASE
WHEN DEPARTMENT_ID=(SELECT DEPARTMENT_ID FROM DEPARTMENTS WHERE LOCATION_ID=1800)
THEN 'CANADA'
ELSE 'USA'
END )LOCATION
FROM EMPLOYEES;
ORDER BY子句的标量子查询
将EMPLOYEES表按照DEPARTMENTS表中的部门名排序
SELECT EMPLOYEE_ID,LAST_NAME,DEPARTMENT_ID
FROM EMPLOYEES E
ORDER BY (SELECT DEPARTMENT_NAME
FROM DEPARTMENTS D
WHERE D.DEPARTMENT_ID=E.DEPARTMENT_ID);
相关子查询
SELECT COLUMN1,COLUMN2,...
FROM TABLE1 外层表别名
WHERE COLUMN1 OPERATOR
(SELECT COLUMN1,COLUMN2
FROM TABLE2 内层表别名
WHERE EXPR1=外层表.EXPR2)
查找薪水比部门平均薪水高的
SELECT LAST_NAME,SALARY,DEPARTMENT_ID
FROM EMPLOYEES OUTER_TABLE
WHERE SALARY>(
SELECT AVG(SALARY)
FROM EMPLOYEES INNER_TABLE
WHERE INNER_TABLE.DEPARTMENT_ID=OUTER_TABLE.DEPARTMENT_ID);
使用EXISTS操作符查找领导(查出来的这些人都是领导)
SELECT EMPLOYEE_ID,LAST_NAME,JOB_ID,DEPARTMENT_ID
FROM EMPLOYEES OUTER
WHERE EXISTS(SELECT ‘X’
FROM EMPLOYEES
WHERE MANAGER_ID=OUTER.EMPLOYEE_ID);
查找没有任何员工的部门
SELECT DEPARTMENT_ID,DEPARTMENT_NAME
FROM DEPARTMENTS D
WHERE NOT EXISTS (SELECT 'X'
FROM EMPLOYEES
WHERE DEPARTMENT_ID=D.DEPARTMENT_ID);
相关UPDATE
CREATE TABLE EMP_I AS SELECT * FROM EMP;
ALTER TABLE EMP_I ADD(DNAME VARCHAR2(20));
UPDATE EMP_I
SET DNAME=(SELECT DNAME FROM DEPT WHERE DEPT.DEPTNO=EMP_I.DEPTNO);
SELECT * FROM EMP_I;
相关DELETE
删除两个表相同的内容
CREATE TABLE EMP1 AS SELECT * FROM EMP;
CREATE TABLE EMP2 AS SELECT * FROM EMP;
DELETE EMP2 WHERE EMPNO<7782;
SELECT * FROM EMP1;
SELECT * FROM EMP2;
DELETE EMP1
WHERE EMPNO=(SELECT EMPNO
FROM EMP2
WHERE EMP2.EMPNO=EMP1.EMPNO);