我有一张桌子message
。我尝试使用contests
外键创建表message_id
。
CREATE TABLE IF NOT EXISTS `message` (
`chat_id` bigint COMMENT 'Unique chat identifier',
`id` bigint UNSIGNED COMMENT 'Unique message identifier',
....
PRIMARY KEY (`chat_id`, `id`),
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
我的桌子contests
CREATE TABLE IF NOT EXISTS `contests` (
`id` INT(11) AUTO_INCREMENT COMMENT 'ID записи',
...
`message_id` bigint UNSIGNED COMMENT 'ID сообщения с кнопкой',
`chat_id` bigint COMMENT 'Так надо',
...
PRIMARY KEY (`id`),
FOREIGN KEY (`message_id`) REFERENCES `message` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`chat_id`) REFERENCES `message` (`chat_id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
错误:使用外键约束创建表'admin_bot / contests' 失败。引用表中没有索引引用 列显示为第一列。
答案 0 :(得分:0)
您需要使用表的主键在表的外键中引用它。您的SQL需要如下所示:
CREATE TABLE IF NOT EXISTS `contests` (
`id` INT(11) AUTO_INCREMENT COMMENT 'ID записи',
...
`message_id` bigint UNSIGNED COMMENT 'ID сообщения с кнопкой',
`chat_id` bigint COMMENT 'Так надо',
...
PRIMARY KEY (`id`),
FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;