[英]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_card
和card_info
在customers_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.