MySQL联合查询
概述
UNION运算符将两个或多个SELECT语句的结果集组合成单个结果集。默认情况下,它会删除重复行。
UNION语法
sql
UNION与UNION ALL
去重联合
sql
-- Removes duplicates
-- Each country appears only once保留重复
sql
-- Keeps all rows including duplicates
-- All countries from both tables比较
| 方面 | UNION | UNION ALL |
|---|---|---|
| 重复 | Removed | Kept |
| 性能 | Slower | Faster |
| 用例 | Unique values | All values |
| 内存 | More | Less |
基本UNION
相同列数
sql
-- Combine results from two tables
-- Different tables, same structure不同列数
sql
-- Must have same number of columns列类型
sql
-- Compatible data types带WHERE的UNION
sql
-- Add conditions to each SELECT
-- Complex conditionsUNION和ORDER BY
sql
-- Sort entire result set
-- Sort individual SELECTs带LIMIT的UNION
sql
-- Top from each source
-- Limited union result组合多个SELECT
sql
-- Three-table union
-- Four-table union带子查询的UNION
sql
-- Union with subqueries
-- Complex subquery union实用示例
日志聚合
sql
多源数据
sql
数据去重
sql
-- Find all unique email addresses基于时间的联合
sql
性能考虑
索引使用
sql
-- Indexes on WHERE columns improve performance
-- Ensure indexes on join/where columns查询优化
sql
-- Use UNION ALL when possible
-- Limit results early编程语言中的UNION
Python / Python
python
# Union in PythonPHP / PHP
php
小结
UNION运算符提供:
结果组合:合并多个SELECT结果 去重:UNION删除重复 性能:UNION ALL更快 排序:ORDER BY在末尾 限制:相同列数和兼容类型 用例:日志聚合、多源数据
上一个:LIKE
下一个:ORDER BY