简体   繁体   中英

How to ensure many to many relationship has the same foreign key

在此处输入图像描述

How can I ensure that the shop_has_product table is from the same company? Is there a way to achieve this is RDBMS or do I need write the insert logic in the application layer.

Thanks you for your time.

In MySQL, you can make a foreign key reference any KEY of the referenced table, not just the primary key. So create a KEY over the id with the company_id in each table.

CREATE TABLE company (
 id INT PRIMARY KEY,
 name VARCHAR(45)
);

CREATE TABLE product (
 id INT PRIMARY KEY,
 company_id INT NOT NULL,
 KEY (id, company_id),
 FOREIGN KEY (company_id) REFERENCES company(id)
);
    
CREATE TABLE shop (
 id INT PRIMARY KEY,
 name VARCHAR(45),
 company_id INT NOT NULL,
 KEY (id, company_id),
 FOREIGN KEY (company_id) REFERENCES company(id)
);

Then add a company_id column to the many-to-many table, and use the same colum in two foreign keys, one to each of the above tables. Naturally, company_id must have the same value in both foreign keys on a given row.

 CREATE TABLE shop_has_product (
 shop_id INT NOT NULL,
 product_id INT NOT NULL,
 company_id INT NOT NULL,
 PRIMARY KEY (shop_id, product_id),
 FOREIGN KEY (shop_id, company_id) REFERENCES shop(id, company_id),
 FOREIGN KEY (product_id, company_id) REFERENCES product(id, company_id)
);

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