16.MySQL修改字段與複製表

修改表ALTER TABLE

  1. 修改表名
    ALTER TABLE 表名
    RENAME 新表名;

  2. 增加字段
    ALTER TABLE 表名
    ADD 字段名 數據類型 [完整性約束條件…],
    ADD 字段名 數據類型 [完整性約束條件…];
    ALTER TABLE 表名
    ADD 字段名 數據類型 [完整性約束條件…] FIRST;
    ALTER TABLE 表名
    ADD 字段名 數據類型 [完整性約束條件…] AFTER 字段名;

  3. 刪除字段
    ALTER TABLE 表名
    DROP 字段名;

  4. 修改字段
    ALTER TABLE 表名
    MODIFY 字段名 數據類型 [完整性約束條件…];
    ALTER TABLE 表名
    CHANGE 舊字段名 新字段名 舊數據類型 [完整性約束條件…];
    ALTER TABLE 表名
    CHANGE 舊字段名 新字段名 新數據類型 [完整性約束條件…];

示例:

  1. 修改存儲引擎
    mysql> alter table service
    -> engine=innodb; //engine=myisam|memory|....

  2. 添加字段
    mysql> create table student10 (id int);
    mysql> alter table student10
    -> add name varchar(20) not null,
    -> add age int not null default 22;

mysql> alter table student10
-> add stu_num int not null after name; //添加name字段之後

mysql> alter table student10
-> add sex enum('male','female') default 'male' first; //添加到最前面

  1. 刪除字段
    mysql> alter table student10
    -> drop sex;

mysql> alter table service
-> drop mac;

  1. 修改字段類型modify
    mysql> alter table student10
    -> modify age tinyint not null default 22; //注意保留原有的約束條件

mysql> alter table student10
-> modify id int not null primary key ; //修改字段類型、約束、主鍵

  1. 增加約束(針對已有的主鍵增加auto_increment)
    mysql> alter table student10 modify id int not null primary key auto_increment; //錯誤,該字段
    已經是primary key
    ERROR 1068 (42000): Multiple primary key defined

mysql> alter table student10 modify id int not null auto_increment;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0

  1. 增加複合主鍵
    mysql> alter table service2
    -> add primary key(host_ip,port);

  2. 增加主鍵
    mysql> alter table student1
    -> add primary key(id);

  3. 增加主鍵和自動增長
    mysql> alter table student1
    -> modify id int not null primary key auto_increment;

  4. 刪除主鍵[primary key auto_increment]
    a. 刪除自增約束
    mysql> alter table student10 modify id int not null;

    b. 刪除主鍵
    mysql> alter table student10
    -> drop primary key;
    五、複製表
    複製表結構+記錄 (key不會複製: 主鍵、外鍵和索引)
    mysql> create table new_service select * from service;

只複製表結構
mysql> create table new1_service select * from service where 1=2; //條件爲假,查不到任何記

複製表結構,包括Key
mysql> create table t4 like employees;

六、刪除表
DROP TABLE 表名;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章