H
H
hrvasiliy2015-11-21 21:24:38
MySQL
hrvasiliy, 2015-11-21 21:24:38

How to make a composite foreign key?

I'm trying to implement a relationship between transport types using foreign keys. What's the catch? - In the fact that at the moment the ancestors refer to the descendant, it turns out that one descendant has 4 parents - which is nonsense. And interestingly, MySQL Workbench allows you to build such a diagram. The parent must somehow take into account the type of transport, so that when the parent's ID changes, exactly those IDs that correspond to the type change. Can't figure out how to do it.
OG1vUJs.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Vitrenko, 2015-11-21
@Vestail

How do you like that?
And are you sure that different types of transport should be distributed according to different tables? If their fields are not very different, you can think about how to combine everything into one table.

A
Aleksey Ratnikov, 2015-11-22
@mahoho

The scheme specified by you cannot be implemented through FOREIGN KEY, it is possible through triggers on tables of "parents". Or I would recommend putting all parents and their types (if I understood everything correctly and these are their types) in one table with something like this:

CREATE TABLE trasports (
id INT UNSIGNED NOT NULL,
type INT UNSIGNED NOT NULL,

PRIMARY KEY (id, type)
FOREIGN KEY (type) REFERENCES transport_type (id)
);

And make the foreign key in user_transport by two fields:
e55c0a54afd64dbe8850965b0911d345.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question