十五、子查詢EXISTS和IN的使用
一、子查詢 IN
子查詢 IN 允許我們在 WHERE 子句中過濾某個欄位的多個值,語法如下:
SELECT
column_nam
FROM
table_name
WHERE
column_name
IN
(
value1
,
value2
,。。,
valueN
)
如果運算子 in 後面的值來源於某個查詢結果,並非是指定的幾個值,這時就需要用到子查詢。子查詢又成為內部查詢或巢狀查詢,即在 SQL 查詢的 WHERE 子句中嵌入查詢語句。語法如下:
SELECT
column_name
FROM
table_name
WHERE
colunm_name
IN
(
SELECT
column_name
FROM
table_name
[
WHERE
]
)
例如:
有學生表 student 和選修表 elective,表結構如下:
student:
欄位
說明
stu_no
學生編號
name
姓名
elective:
欄位
說明
id
編號
name
課程名稱
stu_no
學生編號
查詢所有選修了課程的學生
select
A
。
*
from
student
A
where
A
。
stu_no
in
(
select
B
。
stu_no
from
elective
B
);
查詢選修了計算機的學生
select
A
。
*
from
student
A
where
A
。
stu_no
in
(
select
B
。
stu_no
from
elective
B
where
B
。
name
=
‘計算機’
);
二、子查詢 EXISTS
EXISTS是子查詢中用於測試內部查詢是否返回任何行的布林運算子。獎助查詢的資料放到子查詢中左條件驗證,根據驗證結果(TRUE或FLASE)來決定著查詢的資料結果是否保留。語法如下:
SELECT
column_name1
FROM
table_name1
WHERE
EXISTS
(
SELECT
*
FROM
table_name2
WHERE
condition
);
例如:
查詢出選修了所有課程的學生
select
A
。
*
from
student
A
where
exists
(
select
B
。
stu_no
from
elective
B
where
A
。
stu_no
=
B
。
stu_no
);
查詢出沒有選修任何課程的學生
select
A
。
*
from
student
A
where
not
exists
(
select
B
。
stu_no
from
elective
B
where
A
。
stu_no
=
B
。
stu_no
);