子查询,也称为内部查询或嵌套查询,是另一个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中文网其他相关文章!