向mariadb/mysql表添加外键

eimct9ow  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(310)

我有三张table:

CREATE TABLE `channels` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active’,
 `description` text DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=485 DEFAULT CHARSET=utf8;

CREATE TABLE `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `content` text DEFAULT NULL,
  `description` text DEFAULT NULL,
  `status` enum('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=128 DEFAULT CHARSET=utf8;

CREATE TABLE `events` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `content` text DEFAULT NULL,
  `timezone` varchar(255) DEFAULT NULL,
  `recurring` tinyint(1) NOT NULL DEFAULT 0,
  `all_day` tinyint(1) NOT NULL DEFAULT 0,
  `starts_at` timestamp NULL DEFAULT NULL,
  `ends_at` timestamp NULL DEFAULT NULL,
  `started_at` timestamp NULL DEFAULT NULL,
  `completed_at` timestamp NULL DEFAULT NULL,
  `status` enum('active','inactive','in_progress','complete') DEFAULT 'active',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=82 DEFAULT CHARSET=utf8;

我想修改events表以添加更多字段,并将外键添加到channel、event\ u type和client\ event\ u type。我试过这个:

alter table `events` 
  add `channel` int unsigned not null, 
  add `event_type` int unsigned not null,
  add `client_event_type` int unsigned not null, 
  add constraint `events_channel_foreign` foreign key `channel` references `channels`(`id`),
  add constraint `events_event_type_foreign` foreign key `event_type` references `categories`(`id`),
  add constraint `events_clientEventType_foreign` foreign key `client_event_type` references `categories`(`id`),

结果是:
sql语法有错误;检查与您的mariadb服务器版本对应的手册,以获得使用“参考”的正确语法 channels ( id ),添加约束 events_event_type_foreign 5号线外线
我做错什么了?谢谢

zpjtge22

zpjtge221#

你错过了论文:

alter table `events` 
  add `channel` int unsigned not null, 
  add `event_type` int unsigned not null,
  add `client_event_type` int unsigned not null, 
  add constraint `events_channel_foreign` foreign key (`channel`) references `channels`(`id`),
  add constraint `events_event_type_foreign` foreign key (`event_type`) references `categories`(`id`),
  add constraint `events_clientEventType_foreign` foreign key (`client_event_type`) references `categories`(`id`)

相关问题