--使用子查詢來查找不肯定的值ide
--子查詢與SELECT語句it
SELECT E.EMP_ID, E.FIRST_NAME, E.LAST_NAME, EP.PAY_RATEclass
FROM EMPLOYEE_TBL E, EMPLOYEE_PAY_TBL EP查詢
WHERE E.EMP_ID = EP.EMP_IDdi
AND EP.PAY_RATE <view
(SELECT PAY_RATE FROM EMPLOYEE_PAY_TBL WHERE EMP_ID = '443679012');vi
下面這個語句會做爲後面範例裏的子查詢co
SELECT PAY_RATE FROM EMPLOYEE_PAY_TBL WHERE EMP_ID = '220984332';editor
--子查詢與INSERT語句let
--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);