tohokuaikiのチラシの裏

技術的ネタとか。

MySQLのForeignキー指定時の自動命名則

今更だけど、MySQLのForeignキーの自動命名則。

たとえば、こんなテーブルを作った時。

CREATE TABLE `author_author_type` ( 
  `id` int (10) unsigned NOT NULL AUTO_INCREMENT,
  `author_id` int (10) unsigned NOT NULL,
  `author_type_id` int (10) unsigned NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`),
  FOREIGN KEY (`author_type_id`) REFERENCES `author_types` (`id`)
) ENGINE = InnoDB; 

一旦作って、show create tableすると

CREATE TABLE `author_author_type` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `author_id` int(10) unsigned NOT NULL,
  `author_type_id` int(10) unsigned NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  KEY `author_id` (`author_id`),
  KEY `author_type_id` (`author_type_id`),
  CONSTRAINT `author_author_type_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`),
  CONSTRAINT `author_author_type_ibfk_2` FOREIGN KEY (`author_type_id`) REFERENCES `author_types` (`id`)
) ENGINE=InnoDB;

というようになる。

自動で作成されるもの

INDEXが張られる。

自前のフィールド名でINDEX名が付けられる。

CONSTRAINTが付けられる

FOREIGNキーを作った順番にibfk_1,ibfk_2…というように自動的に制約名が付けられる。

この制約名とかINDEX名がダサイという場合は、きちんと自分で指定しろってことですね。