MySQL 子查詢 exists的用法介绍
MySQL 子查詢 exists的用法介绍
資料來源: http://www.nowamagic.net/librarys/veda/detail/639
01.這個例子比較了兩個語義類似的查詢。第一個查詢使用EXISTS而第二個查詢使用IN。注意兩個查詢返回相同的信息。
SELECT DISTINCT pub_name
FROM publishers
WHERE EXISTS
(SELECT *
FROM titles
WHERE pub_id = publishers.pub_id
AND type = ‘business’)
SELECT distinct pub_name
FROM publishers
WHERE pub_id IN
(SELECT pub_id
FROM titles
WHERE type = ‘business’)
02.本示例顯示查找與出版商住在同一城市中的作者的兩種查詢方法:第一種方法使用= ANY,第二種方法使用EXISTS。注意這兩種方法返回相同的信息。
SELECT au_lname, au_fname
FROM authors
WHERE exists
(SELECT *
FROM publishers
WHERE authors.city = publishers.city)
SELECT au_lname, au_fname
FROM authors
WHERE city = ANY
(SELECT city
FROM publishers)
03.比較使用EXISTS和IN的查詢〜本示例所示查詢查找由位於以字母B開頭的城市中的任一出版商出版的書名:
SELECT title
FROM titles
WHERE EXISTS
(SELECT *
FROM publishers
WHERE pub_id = titles.pub_id
AND city LIKE ‘B%’)
SELECT title
FROM titles
WHERE pub_id IN
(SELECT pub_id
FROM publishers
WHERE city LIKE ‘B%’)