sql—复合键,其中一个组件是外键

whlutmcx  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(345)

我有一个金融应用程序,我每天都存储股票数据,所以我从 Ticker 以及 Date .
我还需要 Ticker (这是上述复合键的一部分)另一个表的外键,称为 Tickers .
但是,当我在SQLServerManagementStudio中添加外键关系时,它要求我为这两个列提供链接 Ticker 以及 Date ,而ticker表只包含 Ticker (这是我只想绑定的内容)。
你知道我做错了什么吗?这是不可能的吗?
我的表格如下:

CREATE TABLE [dbo].[Tickers](
    [Ticker] [nvarchar](8) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Market] [int] NOT NULL,
    [Locale] [int] NOT NULL,
    [Type] [int] NOT NULL,
    [Active] [bit] NOT NULL,
    [PrimaryExch] [nvarchar](50) NOT NULL,
    [Updated] [datetime2](7) NOT NULL,
    [Currency] [int] NOT NULL,
CONSTRAINT [PK_Tickers] PRIMARY KEY CLUSTERED 
(
    [Ticker] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[AggregateDay](
    [Ticker] [nchar](8) NOT NULL,
    [Date] [date] NOT NULL,
    [Volume] [decimal](18, 0) NULL,
    [Open] [decimal](18, 0) NULL,
    [Close] [decimal](18, 0) NULL,
    [High] [decimal](18, 0) NULL,
    [Low] [decimal](18, 0) NULL,
    [Samples] [int] NULL,
 CONSTRAINT [PK_AggregateDay] PRIMARY KEY CLUSTERED 
(
    [Ticker] ASC,
    [Date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

mepcadol

mepcadol1#

设置中的一个问题是父列和子列的数据类型不同: [dbo].[Tickers]([Ticker])[nvarchar](8) ,而 [dbo].[AggregateDay](Ticket)[nchar](8) .
如果将两种数据类型对齐,则可以创建关系,如下所示:

CREATE TABLE [dbo].[AggregateDay](
    [Ticker] [nvarchar](8) NOT NULL 
        REFERENCES [dbo].[Tickers]([Ticker]),  -- foreign key declaration
    [Date] [date] NOT NULL,
    [Volume] [decimal](18, 0) NULL,
    [Open] [decimal](18, 0) NULL,
    [Close] [decimal](18, 0) NULL,
    [High] [decimal](18, 0) NULL,
    [Low] [decimal](18, 0) NULL,
    [Samples] [int] NULL,
CONSTRAINT [PK_AggregateDay] PRIMARY KEY CLUSTERED 
    ([Ticker] ASC, [Date] ASC)
    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) 
    ON [PRIMARY]
) ON [PRIMARY]

db小提琴演示

相关问题