Skip to content

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

比较

方面UNIONUNION ALL
重复RemovedKept
性能SlowerFaster
用例Unique valuesAll values
内存MoreLess

基本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 conditions

UNION和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 Python

PHP / PHP

php

小结

UNION运算符提供:

结果组合:合并多个SELECT结果 去重:UNION删除重复 性能:UNION ALL更快 排序:ORDER BY在末尾 限制:相同列数和兼容类型 用例:日志聚合、多源数据


上一个:LIKE

下一个:ORDER BY