集合运算

    数学上,两个集合 A 和 B 的并集是含有所有属于 A 或属于 B 的元素。下面是一个 UNION 的例子:

    TiDB 支持 UNION ALLUNION DISTINCT 并集,两者区别在于 UNION DISTINCT 会对并集结果去重复,而 UNION ALL 不会。TiDB 中默认使用 UNION DISTINCT

    1. create table t1 (a int);
    2. create table t2 (a int);
    3. insert into t1 values (1),(2);
    4. insert into t2 values (1),(3);

    若 A 和 B 是集合,则 A 与 B 的差集是由所有属于 A 但不属于 B 的元素组成的集合。

    1. | a |
    2. +---+
    3. | 2 |
    4. +---+
    5. 1 rows in set (0.00 sec)

    差集 (EXCEPT) 暂时不支持 EXCEPT ALL

    交集 (INTERSECT) 暂时不支持 INTERSECT ALL。交集 (INTERSECT) 的计算优先级大于差集 (EXCEPT) 和并集 (UNION)。

    1. select * from t1 union all select * from t1 intersect select * from t2;
    2. +---+
    3. | a |
    4. +---+
    5. | 1 |
    6. | 2 |
    7. +---+
    8. 3 rows in set (0.00 sec)

    TiDB 支持使用括号修改集合运算的优先级,如同四则运算中先计算括号部分,集合运算也先计算括号内的部分。

    1. (select * from t1 union all select * from t1 intersect select * from t2) order by a limit 2;
    2. +---+
    3. | a |
    4. +---+
    5. | 1 |
    6. | 1 |