我有一张机器数据表:
machines
----------
id
owner_id
// other data
我们还有来自德国和法国的官方机器数据。两者具有相同的信息:
# Machine data (for german and french machines)
- machine_id: to tie to machines table
- record_number: unique number for each machine, different format for each country
- machine_name: the name of the machine
- market_id: id associated with the machine market, different format for each country
# Market data (also for german and french machines)
- market_id: machine market id, different format for each country
- market_name: name of the market
- specific country information that is different for France and Germany
起初我认为关系模式如下所示:
machines
---------
machine_id
owner_id
// other data
machine_information
---------
machine_id
record_number
country (German or France)
machine_name
market_id
france_markets
---------
id
market_name
// France specific column data
german_markets
---------
id
market_name
// German specific column data
但这会使过滤数据变得非常困难,因为在获取机器信息时,我们不知道我们必须加入哪个市场表。
我还想将 machines_information 分成 2 个,每个国家一个
machines
---------
machine_id
owner_id
// other data
france_machine_information
---------
machine_id
record_number
machine_name
market_id
german_machine_information
---------
machine_id
record_number
machine_name
market_id
france_market
----------
id
market_name
// France specific column data
german_market
----------
id
market_name
// German specific column data
但是这样也有同样的问题,因为在获取机器信息的时候,我们并不知道要加入哪个机器信息表。
这种设计有好的解决方案吗?
谢谢你!
这称为多态关联或超类型/子类型,通常通过在 1:1 关系中使用基表和多个子表来解决。
这里一个众所周知的技巧是将
Type
列添加到基表作为主键的一部分,并Type
在子表中使用计算列。在您的情况下,该
Type
列实际上是国家/地区,因此您可以这样做请注意以下事项:
country
不需要代理键,两个字母的国家代码作为 PK 是完美的。machine_information
不需要单独的主键,因为它的 PK 由机器和国家代码组成。france_market
并且germany_market
两者具有相同的 PK,但是国家代码是一个固定的计算列。machine_information
.machine_information
其中之一。france_market
germany_market