提示:
mysql表操作
一、创建表
create table [if not exists] 表名(
字段名 字段类型 [字段约束] [comment '注释'] [索引类型],
[primary key 字段名 ,]
[index 索引名 (字段名 [,字段名]),]
[unique 索引名 (字段名 [,字段名]),]
);
示例:
create table user(
id int(11) unsigned auto_increment not null comment '主键' ,
username char(20) not null,
usernickname varchar(200) not null unique,
birth_date date not null,
primary key (id),
index username_index(username),
index username_birth_date_index(username,birth_date),
unique username_birth_date_unique(usernickname,birth_date)
)
提示: primary key(主键索引) 和unique(唯一索引)是可以直接写到字段名那行,常规索引是需要在声明完所有字段后,使用index 进行声明
索引帮助mysql高效获取数据排好序的数据结构。
二、编辑表(alter)
修改表语法:alter table 表名 action;
1.添加字段
alter table 表名 add 字段名 <建表语句> [FIRST|AFTER 列名]
代码如下(示例):
alter table user add telno char(11) not null after usernickname;
2.修改字段(除字段名)
alter table 表名 modify 字段名 <建表语句>
代码如下(示例):
alter table user change telno varchar(11) not null after birth_date;
3.修改字段(并修改字段名)
alter table 表名 change 旧字段名 新字段名 <建表语句>
代码如下(示例):
alter table user change telno mobile varchar(11) not null after borth_date;
4.给表重命名
alter table 表名 rename as 新表名
代码如下(示例):
alter table user rename as user_employee;
三、表约束
1. unsigned 无符号类型
(用于设置数值类型,不允许出现负数)
2. zerofill 自动用0补齐
(设置数值类型,在数值之前自动用0补齐不足的位数)