--使用子查询来查找不确定的值
--子查询与SELECT语句
SELECT E.EMP_ID, E.FIRST_NAME, E.LAST_NAME, EP.PAY_RATE
FROM EMPLOYEE_TBL E, EMPLOYEE_PAY_TBL EP
WHERE E.EMP_ID = EP.EMP_ID
AND EP.PAY_RATE <
(SELECT PAY_RATE FROM EMPLOYEE_PAY_TBL WHERE EMP_ID = '443679012');
下面这个语句会作为后面范例里的子查询
SELECT PAY_RATE FROM EMPLOYEE_PAY_TBL WHERE EMP_ID = '220984332';
--子查询与INSERT语句
--INSERT语句将子查询返回的结果插入到另一个表
INSERT INTO RICH_EMPLOYEES
SELECT E.EMP_ID, E.LAST_NAME, E.FIRST_NAME, EP.PAY_RATE
FROM EMPLOYEE_TBL E, EMPLOYEE_PAY_TBL EP
WHERE E.EMP_ID = EP.EMP_ID
AND EP.PAY_RATE >
(SELECT PAY_RATE FROM EMPLOYEE_PAY_TBL WHERE EMP_ID = '220984332');
--子查询与UPDATE语句
--子查询与UPDATE语句配合使用来更新一个表里的一个或多个字段
--在UPDATE语句中使用子查询
--将以下查询用于UPDATE语句的子查询
SELECT EMP_ID FROM EMPLOYEE_TBL WHERE CITY = 'INDIANAPOLIS';
UPDATE EMPLOYEE_PAY_TBL
SET PAY_RATE = PAY_RATE * 1.1
WHERE EMP_ID IN
(SELECT EMP_ID FROM EMPLOYEE_TBL WHERE CITY = 'INDIANAPOLIS');
--子查询与DELETE语句
--从表EMPLOYEE_PAY_TBL删除BRANDON GLASS的记录
DELETE FROM EMPLOYEE_PAY_TBL
WHERE EMP_ID = (SELECT EMP_ID
FROM EMPLOYEE_TBL
WHERE LAST_NAME = 'GLASS'
AND FIRST_NAME = 'BRANDON');
1 row deleted
SELECT CUST_ID, CUST_NAME
FROM CUSTOMER_TBL
WHERE CUST_ID IN
(SELECT O.CUST_ID
FROM ORDERS_TBL O, PRODUCTS_TBL P
WHERE O.PROD_ID = P.PROD_ID
AND O.QTY * P.COST > (SELECT SUM(COST) FROM PRODUCTS_TBL));
--关联子查询
--关联子查询是依赖于主查询里的信息的子查询
--返回订购超过十件物品的顾客的姓名
SELECT C.CUST_NAME
FROM CUSTOMER_TBL C
WHERE 10 <
(SELECT SUM(O.QTY) FROM ORDERS_TBL O WHERE O.CUST_ID = C.CUST_ID);
本文出自 “技术小站” 博客,谢绝转载!