x-to-x-relationships

One-to-one: Use a foreign key to the referenced table:

student: student_id, first_name, last_name, address_id address: address_id, address, city, zipcode, student_id # you can have a

                                                    # "link back" if you need

You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).

Example

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY,
    Name varchar2(25),
    Address varchar2(30),
    TermBegin date,
    TermEnd date
);

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID),
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin)
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:

teachers: teacher_id, first_name, last_name # the "one" side classes: class_id, class_name, teacher_id # the "many" side

Example

Many-to-many: Use a junction table (example):

student: student_id, first_name, last_name classes: class_id, name, teacher_id student_classes: class_id, student_id # the junction table

Example queries:

Example

Many to ones

Last updated

Was this helpful?