學習來源: Codedata - MySQL 超新手入門(10)子查詢
SELECT Code, Population
FROM country
WHERE Population > ( SELECT Population
FROM country
WHERE Code = 'USA' )
子查詢大部份使用在提供判斷條件用的資料,在「WHERE」和「HAVING」子句中,都可能出現子查詢
比較運算子
「IN」運算子
SELECT Name
FROM country
WHERE Code IN (SELECT CountryCode
FROM city
WHERE Population > 90000)
其它運算子
ALL
: 子查詢的結果用 AND
SELECT *
FROM outertable
WHERE n 比較運算子 ALL (SELECT n
FROM innertable)
ANY
, SOME
: 子查詢的結果 OR,「=ANY」 的效果與 「IN 」相同
SELECT *
FROM outertable
WHERE n 比較運算子 ANY (SELECT n
FROM innertable )
多欄位子查詢
SELECT Name
FROM country
WHERE (Region, GovernmentForm) = ( SELECT Region, Government
FROM country
WHERE Name = 'Iraq')
SELECT Continent, Name, GNP
FROM country
WHERE (Continent, GNP) IN (SELECT Continent, MAX(GNP)
FROM country
GROUP BY Continent)
SELECT ( SELECT Population FROM country WHERE Name = 'India')/
( SELECT SUM(Population) FROM country)
子查詢回傳的結果會被當成一個「表格」
SELECT Name, GNP
FROM ( SELECT *
FROM country
WHERE Contient = 'Asia' ) asiacountry
ORDER BY GNP DESC
LIMIT 10
在使用「INSERT」、「UPDATE」與「DELETE」敘述執行新增、修改與刪除資料時,也可以依照需要使用子查詢來簡化資料維護的敘述。
INSERT [INTO] 表格名稱
ON DUPLICATE KEY UPDATE 欄位 = 運算式[]
INSERT INTO mycountry
( SELECT Code, Name, Continent, Region, Population, GNP
FROM country
WHERE Continent = 'Asia')
UPDATE [IGNORE] 表格名稱
SET 欄位名稱 = 運算式|DEFAULT [,...]
WHERE 條件
UPDATE cmdev.emp
SET salary = salary * 1.05
WHERE deptno = ( SELECT deptno
FROM cmdev.dept
WHERE dname = 'SALES')
DELETE [IGNORE] FROM 表格名稱
WHERE 條件
DELETE FROM cmdev.emp
WHERE deptno = ( SELECT deptno
FROM cmdev.dept
WHERE empno = 'SAKES')
需要使用外層查詢的資料來執行判斷的工作,這樣的敘述稱為「關聯子查詢、correlated subqueries」
SELECT Name
FROM country c
WHERE [NOT] EXISTS ( SELECT *
FROM city
WHERE CountryCode = c.Code AND
Population > 80000 )
一些子查詢完成的工作,也可以改用其它的作法來完成