Answer the question
In order to leave comments, you need to log in
How to refer to a composite key?
Good afternoon experts.
When learning SQL, I asked myself a question, but could not find an answer (oddly enough...):
we have 3 tables: users, professions, user_professions (for example). There is a many-to-many relationship between users and professions through the user_professions table. Accordingly, user_professions has a composite PRIMARY KEY in the form (users_id, profession_id). But there are situations when the connecting table is also a separate entity and someone will have to refer to it through FOREIGHN KEY. But how then to refer to the composite key?
Answer the question
In order to leave comments, you need to log in
dev.mysql.com/doc/refman/5.7/en/create-table-forei...
CREATE TABLE product (
category INT NOT NULL, id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)
) ENGINE=INNODB;
CREATE TABLE customer (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE product_order (
no INT NOT NULL AUTO_INCREMENT,
product_category INT NOT NULL,
product_id INT NOT NULL,
customer_id INT NOT NULL,
PRIMARY KEY(no),
INDEX (product_category, product_id),
INDEX (customer_id),
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (customer_id)
REFERENCES customer(id)
) ENGINE=INNODB;
And why is there a problem with a reference to a composite key? :) The mechanism is exactly the same.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question