MySQL EXISTS 運算子
MySQL EXISTS 運算子
EXISTS
運算子用於測試子查詢是否返回任何記錄。
如果子查詢返回一個或多個記錄,EXISTS
運算子返回 TRUE。
EXISTS 語法
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
演示資料庫
Below is a selection from the "Products" table in the Northwind sample database (以下是 Northwind 示例資料庫中的 "Products" 表的選擇結果)
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
以及“Suppliers”表中的一部分資料:
SupplierID | SupplierName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | London | EC1 4SD | UK |
2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA |
3 | Grandma Kelly's Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA |
4 | Tokyo Traders | Yoshi Nagase | 9-8 Sekimai Musashino-shi | 東京 | 100 | Japan |
MySQL EXISTS 示例
以下 SQL 語句返回 TRUE,並列出供應商中價格低於 20 的產品
示例
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
自己動手試一試 »
以下 SQL 語句返回 TRUE,並列出供應商中價格等於 22 的產品
示例
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);
自己動手試一試 »