简体   繁体   English

我无法在 SQL Server 中的 2 个表之间建立复合关系

[英]I can not make a composite relationship between 2 tables in SQL Server

I have the next schema where I want to relation the tables COMPANIES_COUNTRIES and TIME_TRACKING_REQUEST_TYPE by CountryId and CompanyId .我的下一个模式,我想相关的表COMPANIES_COUNTRIESTIME_TRACKING_REQUEST_TYPE通过CountryIdCompanyId

DB Schema数据库架构

The scripts for both tables are the next:两个表的脚本如下:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[COMPANIES_COUNTRIES]
(
    [CountryId] [int] NOT NULL,
    [CompanyId] [int] NOT NULL,
    [Active] [bit] NOT NULL,
    [DateCreated] [datetime] NULL,
    [DateUpdated] [datetime] NULL,

    CONSTRAINT [PK_COMPANIES_COUNTRIES] 
        PRIMARY KEY CLUSTERED ([CountryId] ASC, [CompanyId] 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

ALTER TABLE [dbo].[COMPANIES_COUNTRIES] 
    ADD CONSTRAINT [DF_COMPANIES_COUNTRIES_Active] DEFAULT ((1)) FOR [Active]
GO

ALTER TABLE [dbo].[COMPANIES_COUNTRIES]  WITH CHECK 
    ADD CONSTRAINT [FK_COMPANIES_COUNTRIES_COMPANIES] 
        FOREIGN KEY([CompanyId]) REFERENCES [dbo].[COMPANIES] ([Id])
GO

ALTER TABLE [dbo].[COMPANIES_COUNTRIES] CHECK CONSTRAINT [FK_COMPANIES_COUNTRIES_COMPANIES]
GO

ALTER TABLE [dbo].[COMPANIES_COUNTRIES] WITH CHECK 
    ADD CONSTRAINT [FK_COMPANIES_COUNTRIES_COUNTRIES] 
        FOREIGN KEY([CountryId]) REFERENCES [dbo].[COUNTRIES] ([Id])
GO

ALTER TABLE [dbo].[COMPANIES_COUNTRIES] CHECK CONSTRAINT [FK_COMPANIES_COUNTRIES_COUNTRIES]
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'List of countries assigned to each company' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'COMPANIES_COUNTRIES'
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[TIME_TRACKING_REQUEST_TYPE]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [CompanyId] [int] NOT NULL,
    [CountryId] [int] NOT NULL,
    [Code] [nchar](3) NOT NULL,
    [Description] [nvarchar](200) NOT NULL,
    [Active] [bit] NOT NULL,

    CONSTRAINT [PK_TIME_TRACKING_REQUEST_TYPE_1] 
        PRIMARY KEY CLUSTERED ([Id] 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

ALTER TABLE [dbo].[TIME_TRACKING_REQUEST_TYPE] 
    ADD CONSTRAINT [DF_TIME_TRACKING_REQUEST_TYPE_Active]  DEFAULT ((1)) FOR [Active]
GO

I tried to make a composite relationship with next script but didn't work:我试图与下一个脚本建立复合关系,但没有奏效:

ALTER TABLE TIME_TRACKING_REQUEST_TYPE WITH CHECK 
    ADD CONSTRAINT [FK_TIME_TRACKING_REQUEST_TYPE_COMPANY_COUNTRY] 
        FOREIGN KEY (CompanyId, CountryId) REFERENCES COMPANIES_COUNTRIES (CompanyId, CountryId);

I get this error (sorry, it is in Spanish):我收到此错误(抱歉,是西​​班牙语):

Msg 1776, Level 16, State 0, Line 1消息 1776,级别 16,状态 0,第 1 行
No hay claves principales ni candidatas en la tabla a la que se hace referencia ('COMPANIES_COUNTRIES') que concuerden con la lista de columnas que hace la referencia en la clave externa 'FK_TIME_TRACKING_REQUEST_TYPE_COMPANY_COUNTRY'. No hay claves principales ni candidatas en la tabla a la que se hace referencia ('COMPANIES_COUNTRIES') que concuerden con la lista de columnas que hace la referencia en la clave externa 'FK_TIME_TRACKING_REQUEST_TYPE_COMPANY_COUNTRY'。

Msg 1750, Level 16, State 0, Line 1消息 1750,级别 16,状态 0,第 1 行
No se pudo crear la restricción o el índice.没有 se pudo crear la restricción o el índice。 Vea los errores anteriores.前部错误。

I thought to put both fields as UNIQUE, but I can not due I can repeat records for the same company and country.我想将两个字段都设置为 UNIQUE,但我不能因为我可以重复同一公司和国家/地区的记录。

Do you why is happening that?你为什么会这样?

Thanks in advance.提前致谢。

Foreign keys reference unique "identifiers".外键引用唯一的“标识符”。 In your case, your identifier is the primary key (CountryId, CompanyId) on COMPANIES_COUNTRIES.在您的情况下,您的标识符是 COMPANIES_COUNTRIES 上的主键(CountryId、CompanyId)。 Your foreign key should point to that and not to (CompanyId, CountryId)你的外键应该指向那个而不是 (CompanyId, CountryId)

ALTER TABLE [dbo].[TIME_TRACKING_REQUEST_TYPE] ADD CONSTRAINT [FK_TIME_TRACKING_REQUEST_TYPE_COMPANY_COUNTRY] 
    FOREIGN KEY (CountryId, CompanyId) 
    REFERENCES COMPANIES_COUNTRIES (CountryId, CompanyId);

Create a surrogate key (identity) as a primary key on COMPANIES_COUNTRIES and use it as FK in the child table.在 COMPANIES_COUNTRIES 上创建一个代理键(身份)作为主键,并将其用作子表中的 FK。

The error message is clear.错误信息很清楚。 "There are no primary or candidate keys in the referenced table ('COMPANIES_COUNTRIES') that match the list of columns referenced in the foreign key 'FK_TIME_TRACKING_REQUEST_TYPE_COMPANY_COUNTRY'. Msg 1750, Level 16, State 0, Line 1 Could not create constraint or index. See the errors above. “引用表 ('COMPANIES_COUNTRIES') 中没有与外键 'FK_TIME_TRACKING_REQUEST_TYPE_COMPANY_COUNTRY' 中引用的列列表匹配的主键或候选键。消息 1750,级别 16,状态 0,第 1 行无法创建约束或索引。请参阅上面的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM