主键和外键数据库设计

时间:2015-03-03 17:56:29

标签: sql sql-server-2008

我正在为货币兑换系统创建SQL Server表。

我有一张表如下:

CREATE TABLE [CurrencyKeys]
(
    [Key] [nchar](3) NOT NULL, 
    [Currency] [nvarchar](30) NOT NULL
    CONSTRAINT [PK_Key] PRIMARY KEY ([Key])
);

如何为汇率本身创建表格,该表格引用CurrencyKeys表中的键?

目前我有以下内容:

CREATE TABLE [ExchangeRates]
(
    [DateTime] [datetime]NOT NULL,
    [FromCurrCode] [nchar](3) NOT NULL,
    [ToCurrCode] [nchar] (3) NOT NULL,
    [Rate] [money] NOT NULL
)

我是否还需要创建(FromCurrCodeToCurrCode)作为主键?

4 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要在exchangeRates表上定义外键。

您可以为EACH列定义外键,如下所示:

alter table [ExchangeRates] add constraint fk_ExchangeRates_01 foreign key (fromCurrCode) references CurrencyKeys([Key]);

alter table [ExchangeRates] add constraint fk_ExchangeRates_02 foreign key (toCurrCode) references CurrencyKeys([Key]);

这将为您的exchangeRates表定义外键。

答案 1 :(得分:1)

难道你不想这样做吗?

CREATE TABLE [ExchangeRates]
(
    [DateTime] [datetime]NOT NULL,
    [FromCurrCode] [nchar](3) NOT NULL,
    [ToCurrCode] [nchar] (3) NOT NULL,
    [Rate] [money] NOT NULL,
    Foreign Key([FromCurrCode]) References [CurrencyKeys]([Key]),
    Foreign Key([ToCurrCode]) References [CurrencyKeys]([Key])
)

或者您是否正在尝试询问如何维护ExchangeRates表本身的主键值。你能说清楚吗?

答案 2 :(得分:0)

这取决于您的表是否有多行引用相同(从,到)对(以跟踪不同日期的不同汇率)

如果是这种情况,那么PK可能是(FromCurrCode,ToCurrCode,DateTime)

如果您只保存一个/最后一个汇率,那么(FromCurrCode,ToCurrCode)就足够了。

答案 3 :(得分:0)

您似乎使用自然键代替代理键。

为了使ExchangeRates表使用自然键,您需要使用FromCurrCode和ToCurrCode创建复合主键

CREATE TABLE [ExchangeRates]
(
    [DateTime] [datetime]NOT NULL,
    [FromCurrCode] [nchar](3) NOT NULL,
    [ToCurrCode] [nchar] (3) NOT NULL,
    [Rate] [money] NOT NULL
    CONSTRAINT [PK_ExchangeRates] PRIMARY KEY ([FromCurrCode], [ToCurrCode])
)