MySQL FOREIGN KEY 约束的格式不正确

Dan*_*ray 6 mysql mariadb foreign-key

我有下表定义:

CREATE TABLE `async_task` (
  `idasync_task` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `idasync_type` int(10) unsigned NOT NULL,
  `priority` tinyint(3) NOT NULL,
  `status` enum('todo','doing','failed') NOT NULL DEFAULT 'todo',
  `iduser` int(11) NOT NULL,
  `date_added` datetime NOT NULL,
  PRIMARY KEY (`idasync_task`),
  KEY `priority_id` (`priority`,`idasync_task`),
  KEY `status_type` (`status`,`idasync_type`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Run Code Online (Sandbox Code Playgroud)

我在我的notification表格中添加了一列,我想指向它async_task

ALTER TABLE `notification` ADD COLUMN `async_task_id` BIGINT(20)
Run Code Online (Sandbox Code Playgroud)

当我添加以下外键时:

ALTER TABLE `notification` ADD CONSTRAINT `fk_notification_async_task` 
    FOREIGN KEY (`async_task_id`) REFERENCES `async_task`(`idasync_task`);
Run Code Online (Sandbox Code Playgroud)

我得到:

ERROR 1005 (HY000): Can't create table `my_database`.`#sql-182_2d` 
(errno: 150 "Foreign key constraint is incorrectly formed")
Run Code Online (Sandbox Code Playgroud)

我在别处看过,但只发现错误是:

  1. 您引用的表未创建(不是这种情况)
  2. 您引用的表不是 InnoDB(不是这种情况,notification 和 async_task 都是 InnoDB)
  3. 您没有引用整个主键(不是这种情况,唯一的主键是 ID 列)。

还能是什么?

ype*_*eᵀᴹ 10

引用列和被引用列的类型必须相同(在本例中相同,包括unsigned属性)。

您没有定义notification.async_task_id为 unsigned,所以它是用 (default) 创建的signed。解决这个问题,外键不会引发任何错误。


小智 6

两个表的字符集也可能不同。执行“SHOW CREATE TABLE table1”和“SHOW CREATE TABLE table2”,并注意像 DEFAULT CHARSET=utf8 或 DEFAULT CHARSET=utf8mb4 这样的结尾,它们不一样,并且不能有 FK 指向它们。