1. 程式人生 > >MySQL:DDL的一些整理

MySQL:DDL的一些整理

完整的MongoDB學習筆記位於IT老兵部落格

MySQL:DDL的一些整理。

前言

對於MYSQL對於表結構的修改,一直存在一些函式的地方,這裡,參考一篇外貼,做一下好好的整理。

正文

MySQL ALTER TABLE: ALTER vs CHANGE vs MODIFY COLUMN
Whenever I have to change a column in MySQL (which isn’t that often), I always forget the difference between ALTER COLUMN, CHANGE COLUMN, and MODIFY COLUMN. Here’s a handy reference.

這哥們也遇到了對於alter,change和modify的困擾,所以做了一個整理。

ALTER COLUMN
Used to set or remove the default value for a column. Example:
ALTER TABLE MyTable ALTER COLUMN foo SET DEFAULT ‘bar’;
ALTER TABLE MyTable ALTER COLUMN foo DROP DEFAULT;

alter 常常用來設定或者移除一列的預設值。

CHANGE COLUMN
Used to rename a column, change its datatype, or move it within the schema. Example:
ALTER TABLE MyTable CHANGE COLUMN foo bar VARCHAR(32) NOT NULL FIRST;
ALTER TABLE MyTable CHANGE COLUMN foo bar VARCHAR(32) NOT NULL AFTER baz;

change用來重新命名一列,修改資料型別,或者在模式中移動它。

MODIFY COLUMN
Used to do everything CHANGE COLUMN can, but without renaming the column. Example:
ALTER TABLE MyTable MODIFY COLUMN foo VARCHAR(32) NOT NULL AFTER baz;
The official documentation for ALTER TABLE (for MySQL 5.1) is here.

modify除了不能重新命名一個列,可以做change的所有工作。

官網的摘錄:

CHANGE:
Can rename a column and change its definition, or both.
Has more capability than MODIFY, but at the expense of convenience for some operations. CHANGE requires naming the column twice if not renaming it.
With FIRST or AFTER, can reorder columns.
MODIFY:
Can change a column definition but not its name.
More convenient than CHANGE to change a column definition without renaming it.
With FIRST or AFTER, can reorder columns.
ALTER: Used only to change a column default value.

參考

https://hoelz.ro/ref/mysql-alter-table-alter-change-modify-column
https://dev.mysql.com/doc/refman/5.7/en/alter-table.html