简体   繁体   English

MySQL的'UNION'如何删除多列重复项?

[英]How MySQL's 'UNION' remove duplicates with multiple columns?

I know the main difference between UNION and UNION ALL is the former removes duplicated records, while the latter keeps all. 我知道UNIONUNION ALL之间的主要区别是前者删除重复的记录,而后者保留所有记录。 My question is on how UNION removes duplicated record if there are multiple columns? 我的问题是,如果有多个列, UNION如何删除重复的记录? For example, to union T1(A, B, C) and T2(A, B, C) , 例如,要联合T1(A, B, C)T2(A, B, C)

  1. will MySQL consider (a1, b1, c1) and (a1, b2, c2) duplicates? MySQL将考虑(a1, b1, c1)(a1, b2, c2)重复吗?
  2. if there were duplicates in T1 itself, will MySQL remove this kind of duplicates? 如果T1本身有重复项,MySQL会删除这种重复项吗?

During a UNION (not a UNION ALL ) query, MySQL first combines the records from all the tables involved, and then removes all duplicates. UNION (不是UNION ALL )查询期间,MySQL首先合并所有涉及的表中的记录,然后删除所有重复项。

Consider taking the UNION of the following two tables: 考虑采用以下两个表的UNION

table1
col1 | col2
1    | 1
1    | 1
2    | 2
2    | 2
3    | 4

table2
col1 | col2
1    | 1
1    | 1
3    | 4

Consider the following query 考虑以下查询

SELECT * FROM table1
UNION
SELECT * FROM table2

The output would be this: 输出将是这样的:

col1 | col2
1    | 1
2    | 2
3    | 4

In other words, simply because (1, 1) was duplicated within each separate table does not mean that it appears in duplicate in the result set. 换句话说,仅因为(1, 1)在每个单独的表中重复,并不意味着它在结果集中重复出现。 This output is only consistent with MySQL first combining all records and then removing duplicates. 此输出仅与MySQL先合并所有记录然后删除重复项一致。 This has the side effect that if a record appear in duplicate within one of the tables, it also gets removed. 这样做的副作用是,如果一条记录重复出现在一个表中,则该记录也会被删除。

Demo here: 演示在这里:

Rextester 右旋酯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM