MySQL创建表注意事项和操作表结构

创建表注意事项

  • 表中多个字段用逗号隔开,最后一个字段的结尾不要存在逗号
  • 数据表名不要和字段重名
  • auto_increment 属性 依赖于主键
  • 表名称和字段名避免和关键字冲突

操作表结构

  1. 给表添加新的字段

    alter table 表名 add 字段名 字段类型[ 约束条件] [ 说明 ]

    alter table test9 add username varchar(10) not null default 'xxxx' comment '用户名';

  2. 删除字段

    alter table 表名 drop 字段名;

    alter table test9 drop a;

  3. 更改字段名称

    alter table 表名 change 原字段名 新字段名 字段类型[ 约束条件] [ 说明 ]

    alter table test9 change a age tinyint default 18;

  4. 修改字段信息

    alter table 表名 modify 字段名 字段类型[ 约束条件] [ 说明 ]

    alter table test9 modify age int default 18;

  5. 更改字段位置

    first 排在第一位

    after 在哪个字段后面

    • 放在首位

      alter table 表名 modify 字段名 字段类型[ 约束条件] [ 说明 ] first

      alter table test9 modify age tinyint default 18 first;

    • 在哪个字段后面

      alter table 表名 modify 字段名 字段类型[ 约束条件] [ 说明 ] after 字段名

      alter table test9 modify username varchar(10) default 'xxx' after age;

  6. 添加索引

    • 添加索引名

      alter table 表名 add 索引类型 索引名称(字段名)

      alter table test9 add key k_username(username);

      alter table test9 add unique u_age(age);

    • 不添加索引名

      alter table 表名 add 索引类型(字段名)

      alter table test9 add key(username);

      alter table test9 add unique(age);

  7. 删除索引

    alter table drop key 索引名称;

    alter table test9 drop key u_age;

  8. 修改表和字段字符编码(了解)

    alter table 表名 character set 字符编码;

    alter table 表名 modify 字段名 字段类型[ 约束条件] [ 说明 ] character set utf8;

posted @ 2022-03-16 11:02  寻月隐君  阅读(456)  评论(0编辑  收藏  举报