将外键添加到MariaDB / MySQL表

时间:2018-04-26 08:34:48

标签: mysql sql mariadb

我有3张桌子:

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;

我想更改事件表以添加更多字段并将外键添加到channel,event_type和client_event_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服务器版本,以获得正确的语法   在'references channelsid)附近,添加约束   第5行events_event_type_foreign foreig'

我做错了什么? 感谢

1 个答案:

答案 0 :(得分:1)

你错过了parantheses:

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`)