0
1

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 3 years have passed since last update.

MySQLのSQL文の書き方 メモ

Posted at

CREATE TABLE

CREATE TABLE IF NOT EXISTS users(
    id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    name varchar(30) NOT NULL,
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

ALTER TABLE

カラム追加

ALTER TABLE
    users
ADD
    COLUMN カラム名 INT UNSIGNED NOT NULL;

-- 複数追加
ALTER TABLE
    users
ADD
    COLUMN カラム名 INT UNSIGNED NOT NULL
    COLUMN カラム名 VARCHAR(255);

FOREIGN KEY追加

ALTER TABLE
    users
ADD
    COLUMN usersの参照元にするカラム名 INT UNSIGNED NOT NULL
ADD
    CONSTRAINT フォーリンキー名 FOREIGN KEY (usersの参照元にするカラム名)
    REFERENCES 参照するテーブル (参照するテーブルのカラム)
    ON DELETE CASCADE
    ON UPDATE CASCADE;

カラム削除

ALTER TABLE
    users
DROP
    COLUMN カラム名;

-- 複数削除
ALTER TABLE
    users
DROP
    COLUMN カラム名,
DROP 
    COLUMN カラム名;

FOREIGN KEY削除

ALTER TABLE
    users
DROP
    CONSTRAINT フォーリンキー名 FOREIGN KEY (usersの参照元にするカラム名)
    REFERENCES 参照するテーブル (参照するテーブルのカラム)
    ON DELETE CASCADE
    ON UPDATE CASCADE
DROP
    COLUMN usersの参照元にするカラム名 INT UNSIGNED NOT NULL;
;
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?