Are multiple foreign keys in a single field possible?

前端 未结 3 894
攒了一身酷
攒了一身酷 2021-01-15 16:47

I want to know if there is a way to have multiple values in a single field in a MySQL database where each value is a foreign key referencing one other table.

I am de

3条回答
  •  甜味超标
    2021-01-15 17:05

    What you typically do is set up a many to many relationship with an intermediate linking table. Some thing like the following:

    CREATE TABLE product (
      `id` integer AUTO_INCREMENT NOT NULL,
      -- other cols --
      PRIMARY KEY (`id`)
    );
    
    CREATE TABLE certification (
      `id` integer AUTO_INCREMENT NOT NULL,
      -- other cols --
      PRIMARY KEY (`id`)
    );
    
    CREATE TABLE product_certification (
       `product_id` integer NOT NULL,
       `certification_id` integer NOT NULL,
       PRIMARY KEY (`product_id`, `certification_id`),
       CONSTRAINT `product_id_product_id` 
         FOREIGN KEY (`product_id`) 
         REFERENCES `product` (`id`) ON DELETE CASCADE,
       CONSTRAINT `certification_id_certification_id` 
         FOREIGN KEY (`certification_id`) 
         REFERENCES `certification` (`id`) ON DELETE CASCADE
    );
    

提交回复
热议问题