简体   繁体   English

MySQL 将 2 个主键添加到同一张表中,然后在另一个表中引用它们

[英]MySQL Add 2 Primary Keys to the Same table, then reference to them in another table

I have two tables: customers_card and card_info In the customers_card table I have two primary keys: id and cid .我有两个表: customers_cardcard_infocustomers_card表中我有两个主键: id and cid In the card_info table I have 1 primary key: id .card_info表中,我有 1 个主键: id I want to add 2 foreign keys to the card_info table but I got an error when I try to reference to the card_info.cid我想向card_info表中添加 2 个外键,但是当我尝试引用card_info.cid时出现错误

customers_card table

在此处输入图像描述

card_info table

CREATE TABLE card_info (
   id INT(11) PRIMARY KEY AUTO_INCREMENT,
   uid INT(11) NOT NULL,
   cid VARCHAR(255) NOT NULL,
   number BIGINT NOT NULL,
   holder VARCHAR(255) NOT NULL,
   type VARCHAR(255) NOT NULL,
   provider VARCHAR(255) NOT NULL,
   FOREIGN KEY (uid)
      REFERENCES customers (id)
      ON DELETE CASCADE,
   FOREIGN KEY (cid)
      REFERENCES customers__card (cid)
      ON DELETE CASCADE
);

And the error I get when I try to create the card_info table:当我尝试创建card_info表时出现的错误: 在此处输入图像描述

customers_card

CREATE TABLE `customers_card` (
 `id` int NOT NULL,
 `uid` int NOT NULL,
 `cid` varchar(255) COLLATE utf8mb4_hungarian_ci NOT NULL,
 `cardname` varchar(255) COLLATE utf8mb4_hungarian_ci NOT NULL,
 `cardnum` int NOT NULL,
 `expiry` date NOT NULL,
 `cvc` int NOT NULL,
 `value` int NOT NULL,
 `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  ADD PRIMARY KEY (`id`,`cid`),
  ADD CONSTRAINT `customers__card_ibfk_1` FOREIGN KEY (`uid` REFERENCES `customers` (`id`) ON DELETE CASCADE
)

My summarized question: How can I create a foreign key in the card_info.cid that references to the customers_card.cid without making the customers_card.cid a primary key ?我总结的问题:如何在card_info.cid中创建一个引用customers_card.cid的外键,而不使customers_card.cid成为primary key

Don't use two primary keys.不要使用两个主键。 Set the id to UNIQUE and keep the AUTO_INCREMENT , and set the primary key to the cid , so you can reference to them.id设置为UNIQUE并保留AUTO_INCREMENT ,并将primary key设置为cid ,以便您可以引用它们。

CREATE TABLE `customers_card` (
  `id` int UNIQUE AUTO_INCREMENT,
  `uid` int NOT NULL,
  `cid` varchar(255) PRIMARY KEY,
  `cardname` varchar(255) COLLATE utf8mb4_hungarian_ci NOT NULL,
  `cardnum` int NOT NULL,
  `expiry` date NOT NULL,
  `cvc` int NOT NULL,
  `value` int NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
   ADD CONSTRAINT `customers__card_ibfk_1` FOREIGN KEY (`uid` REFERENCES `customers` (`id`) ON DELETE CASCADE
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM