简体   繁体   English

SQL中的关联表,两个主键

[英]Associative Tables in SQL, 2 primary keys

I am taking an introductory course on SQL and I'm stumped on one of our labs. 我正在参加有关SQL的入门课程,但我陷入了其中的一个实验室。 For this lab, we get an ERD that we need to implement via SQL. 在本实验中,我们获得了需要通过SQL实现的ERD。 The lab requires us to create two tables joined together with an associative table (SQL apparently doesn't like many to many relationships). 该实验室要求我们创建两个与关联表结合在一起的表(SQL显然不喜欢多对多关系)。

In this associative table, both attributes need to be primary keys and foreign keys (Pk, Fk) according the ERD. 在此关联表中,根据ERD,两个属性都必须是主键和外键(Pk,Fk)。 This doesn't make much sense to me (you can't have multiple primary keys) and thus have far I have been unable to implement the ERD by creating multiple primary keys in the table. 这对我来说没有太大意义(您不能有多个主键),因此到目前为止,我无法通过在表中创建多个主键来实现ERD。 Where I am going wrong here internet? 我在这里上网哪里错了?

The code: 编码:

CREATE Table dbo.TargetMailingList
(
     TargetID INT NOT Null 
        Foreign Key References dbo.TargetCustomers(TargetID),

     MailingListsID INT Not NULL 
        Foreign Key References dbo.Mailinglists(MailingListID),

     Primary Key (MailingListID,TargetID), 
);

There are no two primary keys. 没有两个主键。 It is a compound key. 这是一个复合键。 Both the columns are part of the same primary key. 这两个列都是同一主键的一部分。 Check out http://en.wikipedia.org/wiki/Compound_key for more info. 请访问http://en.wikipedia.org/wiki/Compound_key以获得更多信息。

You can create a compound key, as stated by @Juru and create 2 foreign keys: 您可以按照@Juru的说明创建复合键,并创建2个外键:

CREATE TABLE dbo.Table_link
    (
    ndIdTable1 int NOT NULL,
    ndIdTable2 int NOT NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Table_link ADD CONSTRAINT
    PK_Table_link PRIMARY KEY CLUSTERED 
    (
    ndIdTable1,
    ndIdTable2
    ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
ALTER TABLE dbo.Table_link ADD CONSTRAINT
    FK_Table_Table_1 FOREIGN KEY
    (
    ndIdTable1
    ) REFERENCES dbo.Table_1
    (
    ndIdTable1
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO
ALTER TABLE dbo.Table_link ADD CONSTRAINT
    FK_Table_Table_2 FOREIGN KEY
    (
    ndIdTable1
    ) REFERENCES dbo.Table_2
    (
    ndIdTable2
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION 

GO

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

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