建表
所谓建表就是一个声明列的过程。
基本语法
create table 表名(
列名1 列类型1 列1参数,
列名2 列类型2 列2参数,
…
…
列名n 列类型n 列n参数
)engine myisam/… charset gbk/utf8/…
EXAMPLE:
建立一个电子商城的商品电子表。
create table ebusiness (
id int unsigned auto_increment primary key,
product char(20) not null default '',
time_buy date,
time_sell date
)engine myisam charset utf8;
结果如下:
mysql> desc ebusiness;
+-----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| product | char(20) | NO | | | |
| time_buy | date | YES | | NULL | |
| time_sell | date | YES | | NULL | |
+-----------+------------------+------+-----+---------+----------------+
代码解析:
- auto_increment定义列为自增的属性,一般用于主键,数值会自动加1。
- not null设置字段为非缺省值,在操作数据库时如果输入该字段的数据为NULL ,就会报错。
- primary key关键字用于定义列为主键。
- engine设置存储引擎,charset设置编码。
修改表操作
增加列
alter table 表名 add 列名称 列类型 列参数; 加的列在表的最后
alter table 表名 add 列名称 列类型 列参数 after 某列; 把新列加在某列的后面
如果想新建一个列,并且在最前面,用first:
alter table 表名 add 列名称 列类型 列参数 first; 把新列加在最前面
删除列
alter table 表名 drop 列名;
修改列
alter table 表名 modify 列名称 新列类型 新列参数;
修改列名及列类型
alter table 表名change 旧列名 新列名 新类型 新参数;