Quelqu'un peut-il s'il vous plaît me dire comment estabilish 1 to 0..1
et 1 to 1..*
relations entre les tables dans SQL (Server)?
Merci beaucoup.
1 à 1 .. *
Créer une key étrangère à partir d'une table parent à la key primaire de l'enfant (table de search).
CREATE TABLE A ( id int NOT NULL IDENTITY(1,1) PRIMARY KEY, Somecolumn int, SomeOtherColumn Varchar(50), B_id int CONSTRAINT FOREIGN KEY REFERENCES B(id), -- ...other columns ) CREATE TABLE B ( id int NOT NULL IDENTITY(1,1) PRIMARY KEY, Name Varchar(50) )
1 à 0..1
Créer une table avec la key primaire également définie comme une key étrangère à la table parent
CREATE TABLE [Master] ( id int NOT NULL IDENTITY(1,1) PRIMARY KEY, Somecolumn int, SomeOtherColumn Varchar(50), -- ...other columns ) CREATE TABLE [Child] ( id int NOT NULL PRIMARY KEY, OtherColumn Varchar(50), ) ALTER TABLE Child ADD CONSTRAINT FK_Master FOREIGN KEY (id) REFERENCES Master(id)
Un à plusieurs
Cela signifie que le tableau A peut contenir un ou plusieurs loggings relatifs à un logging unique dans le tableau B.
Si vous avez déjà les tables en place, utilisez l'instruction ALTER TABLE pour créer la contrainte de key étrangère:
ALTER TABLE A ADD CONTRAINTE FOREIGN KEY fk_b (b_id) references b (id)
* fk_b: Name of the foreign key constraint, must be unique to the database * b_id: Name of column in Table A you are creating the foreign key relationship on * b: Name of table, in this case b * id: Name of column in Table B