Are multiple foreign keys in a single field possible?

前端 未结 3 866
攒了一身酷
攒了一身酷 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 16:58

    A single field cannot be a foreign key to more than one field in another table. It's just not possible. Since your foreign table has a composite key, your table in question would have to have the same fields as well.

    0 讨论(0)
  • 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
    );
    
    0 讨论(0)
  • 2021-01-15 17:05

    If I understand you correctly, the relation product : product_certification is 1:M you can create a foreign key from product_certification to products via product_id, instead of having product_certification_id in the products table (which is invalid, since the product can have more than 1 certification)

    0 讨论(0)
提交回复
热议问题