子查詢,也稱為內部查詢或巢狀查詢,是另一個SQL查詢中的查詢。它包含在括號內並首先執行以提供外部查詢用於進一步處理的結果。
範例:
找出薪水最高的員工姓名:
SELECT Name FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);
範例:
尋找在超過 5 名成員的部門工作的員工:
SELECT Name FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Members > 5);
範例:
找出收入高於部門平均薪資的員工:
SELECT Name, Salary FROM Employees E WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID = E.DepartmentID);
範例:
尋找員工平均薪資超過 50,000 美元的部門:
SELECT Name FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);
SELECT Name FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Members > 5);
SELECT Name, Salary FROM Employees E WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID = E.DepartmentID);
SELECT DepartmentName FROM Departments WHERE DepartmentID IN ( SELECT DepartmentID FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees) );
SELECT * FROM Products WHERE Price > (SELECT AVG(Price) FROM Products);
子查詢是 SQL 中的一個強大工具,用於將複雜邏輯分解為可管理的部分,實現動態資料分析並促進資料操作。然而,了解何時使用子查詢與連接等替代方案對於獲得最佳查詢效能至關重要。
以上是了解 SQL 子查詢:帶有範例的完整指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!