0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【MYSQL】カラム追加とインデックスと外部キーを同時に行う

Last updated at Posted at 2022-05-04

些細なところで、あれ、どうしたらいいんだとなったので、残しておく。

カラム追加と外部キー名指定とインデックス名を指定したい場合は以下のように書ける。

CREATE TABLE `article_types` (
    `id` int NOT NULL,
    ...
);

ALTER TABLE `articles` 
    ADD COLUMN `article_type_id` INT NOT NULL COMMENT '記事種別',
    ADD INDEX `index_article_type_id` (`article_type_id`), // index名を付けたい場合
    ADD CONSTRAINT `fk_articles_article_type_id` FOREIGN KEY  (`article_type_id`) 
        REFERENCES `article_types` (`id`) 
            ON DELETE RESTRICT
            ON UPDATE CASCADE;

外部キーを設定すると自動でインデックスが作成されます。xxx_ibfkというような名前で。
独自に名前を決めたい場合は、

 ADD INDEX `インデックス名` (`カラム名`)

逆に消すときは

ALTER TABLE `articles`
    DROP FOREIGN KEY `fk_articles_article_type_id`,
    DROP COLUMN `article_type_id`;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?