sql子查询
时间: 2023-07-13 19:04:53 浏览: 105
SQL子查询是指在主查询语句中嵌套一个子查询语句,用来获取更精确的查询结果。子查询可以出现在SELECT、FROM、WHERE和HAVING子句中。子查询可以返回一个单独的值、一组值或一张表,这些返回结果可以用来作为主查询语句中的过滤条件或者计算条件。下面是一些子查询的例子:
1. 查询最大工资:
```
SELECT MAX(salary) FROM employee;
```
2. 查询工资高于平均工资的员工:
```
SELECT * FROM employee WHERE salary > (SELECT AVG(salary) FROM employee);
```
3. 查询每个部门的平均工资:
```
SELECT department, AVG(salary) FROM employee GROUP BY department;
```
4. 查询部门内工资最高的员工:
```
SELECT * FROM employee WHERE salary = (SELECT MAX(salary) FROM employee WHERE department = 'Sales');
```
5. 查询没有销售记录的员工:
```
SELECT * FROM employee WHERE NOT EXISTS (SELECT * FROM sales WHERE sales.employee_id = employee.id);
```
注意,子查询的性能可能不如连接查询,因此应该谨慎使用。
阅读全文