子查询(Subquery)在SQL(结构化查询语言)中是一种常见的查询技术,主要用于以下几种场景:
1. 数据过滤:当需要在主查询中使用查询结果作为条件时,可以使用子查询。例如,找出比某个特定值更大的所有记录。
2. 聚合计算:子查询可以用来计算一组数据的总和、平均值、最大值或最小值,然后在主查询中引用这些值。
3. 连接查询:在连接两个或多个表时,可以使用子查询来指定连接条件,或者获取连接所需的中间结果。
以下是一些使用子查询的例子:
查找比平均工资高的员工:
```sql
SELECT
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
```
找出部门中人数最多的部门:
```sql
SELECT DepartmentID, COUNT() AS EmployeeCount
FROM Employees
GROUP BY DepartmentID
HAVING COUNT() > (SELECT MAX(EmployeeCount) FROM (SELECT DepartmentID, COUNT() AS EmployeeCount FROM Employees GROUP BY DepartmentID) AS SubQuery);
```
在两个表中查找匹配的记录:
```sql
SELECT
FROM Orders
WHERE CustomerID IN (SELECT CustomerID FROM Customers WHERE City = 'New York');
```
计算每个部门的平均工资与整个公司的平均工资的比较:
```sql
SELECT DepartmentID, AVG(Salary) AS AvgSalary, (SELECT AVG(Salary) FROM Employees) AS CompanyAvgSalary
FROM Employees
GROUP BY DepartmentID;
```
使用子查询可以使SQL查询更加灵活和强大,但也要注意合理使用,因为不当的子查询可能会影响查询性能。