问题:
准备数据:
create table tbl_a(
key varchar(100) not null ,
col_1 int not null,
col_2 int not null,
col_3 int not null
);
insert into tbl_a(key, col_1, col_2, col_3)
values('A', 2, 3, 4),
('B', 0, 7, 9),
('C', 5, 1, 6);
/*
key | col_1 | col_2 | col_3
-----+-------+-------+-------
A | 2 | 3 | 4
B | 0 | 7 | 9
C | 5 | 1 | 6
(3 rows)
*/
create table tbl_b(
key varchar(100) not null ,
col_1 int not null,
col_2 int not null,
col_3 int not null
);
insert into tbl_b(key, col_1, col_2, col_3)
values('A', 2, 3, 4),
('B', 0, 7, 9),
('C', 5, 1, 6);
/*
key | col_1 | col_2 | col_3
-----+-------+-------+-------
A | 2 | 3 | 4
B | 0 | 7 | 9
C | 5 | 1 | 6
(3 rows)
*/
问题: 在我们迁移数据库的时候, 我们会判断两个表是否相等. 那么如何比较两张表中的数据是否相等? 虽然这两张表都只有三行数据, 很容易用眼睛看出来, 但是若两张表都有上千,上万, 上亿的数据, 如何比较呢?
解法:
select (select count(*)
from (select *
from tbl_a
union
select *
from tbl_b) tmp) = (select count(*)
from tbl_a) is_equal;
/*
is_equal
----------
t
(1 row)
*/
解析: 若集合S不存在重复元素, 则 S UNION S = S, 继而 S UNION S UNION S UNION … = S. 利用这个幂等性就可以判断两个非重复集合是否相等. 这道题就是根据tbl_a, tbl_b中集合的非重复性与幂等性来判断两个集合是否相等.
疑惑:
若是要比较的两个集合有重复行怎么办? 这里就凸显了主键的重要性❗️