您的当前位置:首页正文

MySQL 创建/修改表, 添加/修改字段

来源:要发发知识网

查看所有数据库

show databases;

切换数据库

use [数据库名称]

查看表当前所有字段

show columns from 表名称

  • 例子:
show columns from em;

查看表创建时字段的默认信息

查看字段是否有默认名称, 查看字段是否可空:
show create table 表名称;
如果字段为不可空, 且没有添加默认值时, 则插入数据时对字段不处理则会报错

  • 例子:
show create table em;

创建表

create table 表名称(
字段名, 数据类型(如果有字符长度则必须加上),
字段名, 数据类型(如果有字符长度则必须加上));

数据类型:
  • 整型:
MySQL数据类型 含义(有符号)
tinyint(m) 1个字节 范围(-128~127)
smallint(m) 2个字节 范围(-32768~32767)
mediumint(m) 3个字节 范围(-8388608~8388607)
int(m) 4个字节 范围(-2147483648~2147483647)
bigint(m) 8个字节 范围(+-9.22*10的18次方)

取值范围如果加了 unsigned,则最大值翻倍,如 tinyint unsigned 的取值范围为(0~255)。
int(m) 里的 m 是表示 SELECT 查询结果集中的显示宽度,并不影响实际的取值范围,没有影响到显示的宽度,不知道这个 m 有什么用。

  • 例子:
create table em(
            empno char(10));

修改表名称

alter table 表名称 rename 新名称;

  • 例子:
alter table test rename test1; --修改表名

添加表字段

alter table 表名称 add 字段名 数据类型(如果有字符长度则必须加上);

  • 例子:
alter table em add ename varchar(20);

修改表字段

修改表字段类型
alter table 表名称 modify 字段名 数据类型(如果有字符长度则必须加上);

  • 例子
alter table em modify empno char(4);

修改表字段名称
alter table 表名称 rename column 旧字段名称 to 新字段名称;

  • 例子
alter table em rename column birthdate to hiredate;