简体   繁体   中英

Is this an example of One To One?

My teacher told me that this code below is an example of one to one relationship:

CREATE TABLE PERSON (ID INT AUTO_INCREMENT, NAME VARCHAR(20) UNIQUE NOT NULL,
CONSTRAINT PK_PERSON PRIMARY KEY (ID));

CREATE TABLE PHRASE (ID INT AUTO_INCREMENT, PHRASE VARCHAR(50) UNIQUE NOT NULL, ID_PERSON INT,
CONSTRAINT PK_PHRASE PRIMARY KEY (ID),
CONSTRAINT FK_PHRASE FOREIGN KEY (ID_PERSON) REFERENCES PERSON(ID));

But this way I can set two phrases to the same person, what make me think that the correct is the answer below:

CREATE TABLE PERSON (ID INT AUTO_INCREMENT, NAME VARCHAR(20) UNIQUE NOT NULL,
CONSTRAINT PK_PERSON PRIMARY KEY (ID));

CREATE TABLE PHRASE (ID INT AUTO_INCREMENT, PHRASE VARCHAR(50) NOT NULL UNIQUE, ID_PERSON INT,
CONSTRAINT PK_PHRASE PRIMARY KEY (ID),
CONSTRAINT FK_PHRASE FOREIGN KEY (ID_PERSON) REFERENCES PERSON(ID),
CONSTRAINT FK_PHRASE2 UNIQUE (ID_PERSON));

Is the second example an one to one relationship or the first?

You are right with your assessment. The 2nd option where you forced ID_PERSON to be unique is 1:1 relationship. Nice work.

You are also right in your assessment that the first method allowed multiple phrases by the same person, which becomes a 1:many relationship.

Alternate theory

create table person (id int primary key, name varchar(20) unique);

create table phrase (id int primary key, phrase varchar(20) unique);

create table person_phrase (person_id int primary key, phrase_id int);

The above will also cause a 1:1 relationship between person and phrase but will have separate tables for person and separate table for phrase. You'd bring together person and phrase as long as one person has one phrase.

This design allows you to start with 1:1 and expand to many:many relationship wherein a person can have many phrases and one phrase could be used by many people. You could expand to many:many by making person_id + phrase_id primary.

Second one is an example of one to one relationship. The first one only guarantees the referential integrity is maintained. That means it will make sure that the value of PERSON_ID should exist in PERSON table , while it allows you to enter multiple PERSON ID in the table.

Second example has foreign key constraint as well as unique key on PERSON ID, which maintains that the PERSON ID should also be unique in PHRASE table.

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