mysql 合并查询
时间: 2024-09-13 11:15:45 浏览: 42
最全的mysql查询语句整理
在MySQL中,合并查询通常是指将两个或更多的数据集通过某种方式进行结合,得到单个结果集的操作。常见的合并查询有以下几种:
1. **UNION**: UNION用于合并两个或更多SELECT语句的结果,并去除重复的行。它们的列数和数据类型必须完全匹配。例如:
```sql
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;
```
2. **UNION ALL**: 类似于UNION,但它保留了所有行,包括重复的。这在不需要去重的情况下效率更高。
```sql
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;
```
3. **JOIN**: JOIN操作则是基于关联字段将表中的记录连接在一起,比如INNER JOIN、LEFT JOIN、RIGHT JOIN等。例如:
```sql
SELECT t1.column1, t2.column2
FROM table1 t1
INNER JOIN table2 t2 ON t1.common_field = t2.common_field;
```
4. **GROUP BY**: 当需要对结果进行分组后再合并时,可以使用GROUP BY和UNION ALL,如计算每个部门的平均工资:
```sql
SELECT department, AVG(salary) as avg_salary
FROM (SELECT department, salary FROM employees WHERE department IN ('Sales', 'Marketing'))
GROUP BY department
UNION ALL
SELECT department, AVG(salary) as avg_salary
FROM (SELECT department, salary FROM employees WHERE department IN ('Engineering'))
GROUP BY department;
```
阅读全文