Viktory
Viktory

Reputation: 59

How to create a new table for relationship between these tables

I have table Work. it's look like

CREATE TABLE work
(
work_id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
type_of_service_conn int NOT NULL,
period_of_execution int NOT NULL,
mechanic_conn int NOT NULL,
spare_conn int NOT NULL,
FOREIGN KEY (mechanic_conn) REFERENCES mechanic(mechanic_id),
FOREIGN KEY (type_of_service_conn) REFERENCES type_of_service(type_of_service_id),
FOREIGN KEY (spare_conn) REFERENCES spares(spare_id),
)

And i have table Spares

CREATE TABLE spares
(
spare_id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
name_of_spare nvarchar NOT NULL,
price_for_spare decimal NOT NULL
)

For example, for repair of the engine are needed bolts, washers and nuts. How to link these tables?

Upvotes: 0

Views: 34

Answers (1)

Nidhoegger
Nidhoegger

Reputation: 5232

What you are looking for are probably 1:n relationships.

You need a third table, that stores what kind of parts are used for what repair_id, e.g.

CREATE TABLE spares_for_work (
    work_id INT NOT NULL,
    spare_id INT NOT NULL,
    count INT NOT NULL,
    FOREIGN KEY (work_id) REFERENCES work(work_id),
    FOREIGN KEY (spare_id) REFERENCES spares(spare_id) );

Then you cant put multiple parts in a work_id. E.g.: you put in spares_for_work:

work_id = 1, spare_id=12, count=1
work_id = 1, spare_id=16, count=12
...

When you then select from spares_for_work the work_id 1, you will get all spares needed for that work.

Upvotes: 1

Related Questions