生成跨多个数据库唯一的主键

Generating a primary key unique across multiple databases

相同结构的操作数据库在多个国家工作。

country A has table Users with column user_id
country B has table Users with column user_id
country C has table Users with column user_id

当来自所有三个数据库的数据被带到暂存区以用于进一步的数据仓库目的时,所有三个操作 table 都集成到一个 table 用户 dwh_user_id 中。

逻辑如下所示:

if record comes from A then dwh_user_id = 1000000 + user_id
if record comes from B then dwh_user_id = 4000000 + user_id
if record comes from c then dwh_user_id = 8000000 + user_id

我有一种强烈的感觉,这是一种非常糟糕的做法。什么是更好的方法? (user_id + country_iso_code 也许吧?)

一般来说,以这种方式将逻辑注入主键是一个糟糕的主意。这真的会让你失败 - 如果国家 A 获得超过 4000000 条用户记录怎么办?

有多种解决方案。

理想情况下,您在所有 table 中包含列 "country",并将其与 ID 一起用作主键。这使主记录和国家记录之间的逻辑保持一致。

如果您使用的是遗留系统,并且无法修改国家 table,但可以修改主系统 table,在其中添加密钥,在加载期间填充它,然后使用国家和ID的组合作为主键。

我们在 Ajilius 中处理这种情况的方法是将元数据列添加到负载中。 SERVER_NAME 或 DATABASE_NAME 等值可能提供足够的唯一信息,使复合键唯一。

另一种方案是在提取或加载时为每一行生成一个 GUID,然后它将唯一地标识每一行。

数据保险库人员喜欢在行中使用散列,但在这种情况下,只有在没有行完全重复的情况下它才有效。

这就是他们制作 Uniqueidentifier 数据类型的原因。参见 here

如果你不能改成那样,我会把每一个都放在不同的 table 中,然后将它们合并到一个视图中。类似于:

create view vWorld
as
select 1 as CountryId, user_id
from SpainUsers
UNION ALL 
select 2 as CountryId, user_id
from USUsers

最有效的方法是:-

If record from Country A, then user * 0 = Hence dwh_user_id = 0.

If record from Country B, then (user * 0)- 1 = Hence dwh_user_id = -1.

If record from Country C, then (user * 0)+ 1 = Hence dwh_user_id = 1.

建议此逻辑假设 dwh_user_id 应该是一个数字字段。