接上一篇内容,前面已经介绍了创建数据库,以及数据库中表格支持的数据类型,在此节中介绍创建数据表格,以及测试表格的几个常见的约束条件。
1.创建表格
在创建表格之前,首先要指定使用的数据库.
命令格式: use 数据库名称;
创建表格的命令和创建数据库的命令一样,都是使用create,但是命令不同,创建表格命令格式如下:
create table table_name(
col_name data_type [字符集] [ 约束性条件 ],
…..
)[engine = innodb] [charset = utf8];
我使用的mysql版本时5.7,默认引擎时innodb,字符集默认为utf-8。
例如:
create table test
(
id int unsigned auto_increment key,
username varchar(5) charset utf8 not null unique,
password char(32) char set utf8 unique not null,
email varchar(10) character set utf8 not null
)ENGINE=INNODB;
创建表格成功之后,可
show tables;
库的表格,也可以通过命令
desc 表格名称;
show create table 表格名称;
显示数据库表格的详细信息。
下面测试约束性条件:unique、not null、unsigned、auto_increment、key、primary key、default。
unique表示列值不能插入与其他列相同的值,null值除外,
not null表示列值不能为空
unsigned只能修饰数值类型,表示哪一列不能为负数
auto_increment只能修饰整型,而且需要和key同时使用,
key普通索引
primary key主键,一张表只能有一个主键,主键可以有一列或者多列组成,
defualt用于修饰列的默认值,当插入数据是,如果没有提供某一列的值,而且不是auto_increment类型的值,则使用默认值,如果建立表格时没有提供默认值,则使用null值,如果此时又添加not null的约束条件是,则会报错。
create table test_create(
id int unsigned auto_increment key comment '编号',
usrname varchar(20) unique not null comment '用户名',
addr varchar(20) not null default '北京' comment '地址',
salary float unsigned not null comment '薪水',
age tinyint not null default 18 comment '年龄',
married tinyint(1) not null default 0 comment '0表示未婚,1表示已婚, 2表示保密',
sex set('男', '女', '保密') not null default '男' comment '性别'
)engine=innodb charset=utf8;
comment用于给表格列添加注释,创建上述表格之后,可以采用上面讲到的显示表格的详细命令,看看表格列的约束条件。