【问题标题】:Sharing composite foreign key based on the same columns across multiple tables in MS SQL Server在 MS SQL Server 中跨多个表共享基于相同列的复合外键
【发布时间】:2015-03-05 18:58:38
【问题描述】:

我有一个包含多个表的数据库,其中包含有关不同工具(货币、基金、股票等)的信息。所有仪器都有TypeId 字段,它们代表仪器的唯一键。我还有一张表InstrumentMeta,它收集了所有以(Type,Id) 作为主键的工具的统计信息。

  1. Instrument_1 - Type(int), Id(string), Values, ...
  2. Instrument_2 - Type(int), Id(string), Code, ...
  3. ...
  4. InstrumentMeta - Type(int), Id(string), PerformanceValue1, PerformanceValue2, PerformanceValue3

是否可以为InstrumentMeta 表和所有Instrument_ 表创建基于同一对(Type, Id) 的外键?

【问题讨论】:

  • 请始终告诉我们您使用的是什么数据库引擎,以便我们提供更相关的答案。提供一些示例数据也有助于为您的问题提供一些背景信息。

标签: sql sql-server foreign-keys composite-key


【解决方案1】:

简短的回答是“不!”这与复合键无关,对所有键都是如此。外键必须指定该键所引用的 ONE 表。

但是,您必须拥有一个包含所有不同键值组合的“主”表。据我所见,这看起来可能是元表,因为它必须包含所有类型/Id 值。所以这是主表,所有“instrument_x”表都是子表。

子表包含引用回主表的 FK。这是一个例子。

create table Meta(
    Type    varchar( 16 ) not null,
    ID      smallint not null,
    <other meta fields>,
    constraint PK_Meta primary key( Type, ID ),
    constraint CK_Meta_Type check( Type in( 'Currency', 'Fund', 'Equity' ))
);
create table Currencies(
    Type    varchar( 16 ) not null,
    ID      smallint not null,
    <other currency fields>,
    constraint PK_Currencies primary key( Type, ID ),
    constraint CK_Currencies_Type check( Type = 'Currency' ),
    constraint FK_Currencies_Meta foreign key( Type, ID )
        references Meta( Type, ID )
);
create table Funds(
    Type    varchar( 16 ) not null,
    ID      smallint not null,
    <other fund fields>,
    constraint PK_Funds primary key( Type, ID ),
    constraint CK_Funds_Type check( Type = 'Fund' ),
    constraint FK_Funds_Meta foreign key( Type, ID )
        references Meta( Type, ID )
);

等等。

这种设计会强制您在元表中输入“Currency:42”行,然后才能在 Currencies 表中创建 ID 42。但这可能是一个非常好的主意。

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 2014-02-26
    • 2020-06-16
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2023-03-06
    • 2012-03-07
    相关资源
    最近更新 更多