gpt4 book ai didi

mysql - 无法使用 FOREIGN KEY 在 MySQL 中添加外键约束

转载 作者:行者123 更新时间:2023-11-29 06:19:09 26 4
gpt4 key购买 nike

我刚刚创建了这个表:

CREATE TABLE `t_application` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`application_desc` varchar(255) DEFAULT NULL,
`application_key` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_cotl49evfo7w4plf6213uaruc` (`application_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

然后我想创建这个:

CREATE TABLE `t_device` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`device_key` varchar(50) DEFAULT NULL,
`device_type` varchar(50) DEFAULT NULL,
`application_id` int(11) unsigned NOT NULL,
`device_desc` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `application_id` (`application_id`),
CONSTRAINT `t_device_app` FOREIGN KEY (`application_id`) REFERENCES `t_application` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

但这是不可能的,因为我得到了这个错误:

Cannot add foreign key constraint

最佳答案

FK 列必须与引用表中的 PK 具有相同的类型:

Using FOREIGN KEY Constraints

Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

你有:int(11) <> int(11) unsigned

CREATE TABLE `t_application` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`application_desc` varchar(255) DEFAULT NULL,
`application_key` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_cotl49evfo7w4plf6213uaruc` (`application_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `t_device` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`device_key` varchar(50) DEFAULT NULL,
`device_type` varchar(50) DEFAULT NULL,
`application_id` int(11) unsigned NOT NULL,
`device_desc` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `application_id` (`application_id`),
CONSTRAINT `t_device_app` FOREIGN KEY (`application_id`)
REFERENCES `t_application` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

SqlFiddleDemo

因此您可以将:t_application.id 更改为 int(11) unsigned

t_deviceapplication_idint(11)

关于mysql - 无法使用 FOREIGN KEY 在 MySQL 中添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com