简体   繁体   中英

Two Composite Primary Key in SQL

I am trying to define table as follows:

CREATE TABLE dbo.[User]
(
  Id int NOT NULL IDENTITY PRIMARY KEY,
  Name nvarchar(1024) NOT NULL
);

CREATE TABLE [Group] 
(
  Id int NOT NULL IDENTITY PRIMARY KEY,
  Name nvarchar(1024) NOT NULL
);

CREATE TABLE [UserToGroup]
(
  Name VARCHER(20)
  UserId int NOT NULL,
  GroupId int NOT NULL,
  PRIMARY KEY CLUSTERED ( UserId, Name),
  PRIMARY KEY CLUSTERED ( GroupId, Name),
  FOREIGN KEY ( UserId ) REFERENCES [User] ( Id ) ON UPDATE  NO ACTION  ON DELETE  CASCADE,
  FOREIGN KEY ( GroupId ) REFERENCES [Group] ( Id ) ON UPDATE  NO ACTION  ON DELETE  CASCADE
);

How can i create table with two Composite Primary Key?

 Name VARCHAR(20) NOT NULL,
 UserId int NOT NULL,
 GroupId int NOT NULL,
 UNIQUE ( UserId, Name),
 UNIQUE ( GroupId, Name)

In the relational model and in SQL there is no logical difference between one key and another so there's no very strong reason to have a different syntax for specifying one key over any other. However, for better or worse, the authors of the SQL standard decided to make a limitation that the PRIMARY KEY constraint syntax can only be used once per table and that where you need more than one key you have to use one or more UNIQUE constraints instead. Arguably it would be desirable to drop that limitation but since it's fundamentally just a bit of syntactical sugar that's unlikely to happen any time soon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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