一.数据类型
1.整型
由小到大:tinyInt、smallint、mediumint、int
2.小数
float(m,d)、double(m,d)
这里要注意,MySQL数据库中的浮点型和编程语言中的浮点型不一样,其中m表示数字长度,d表示小数位数,例如float(5,2)最大值999.99。
3.文章
数据库当然不只能存些简单的数据,还可以存储文章,text就是文章的数据类型。
4.文件
blob是二进制文件类型,但是最多存4G,所以一般不会存在表中。
5.时间
timestamp、date都是用来存时间的数据类型,date存的时间比较大,日、月、年之类的,而timestamp存的时间比较精确,可以精确到毫秒。
二.字段约束
1.comment
顾名思义,comment是用来写注释的字段约束,如果在字段名后不加注释,一旦字段特别多,时间长了就不容易认清某一变量的具体意思,用法如下:
create table student(
id char(36) comment 'id 标识列',
user_name varchar(12) comment '用户名',
password varchar(15) comment '密码',
address varchar(120) comment '地址'
)
2.not null
该约束符号代表该字段处的数据不允许为空,这时给表添加数据的时候如果user_name或password为null则就会报错:
create table student(
id char(36) comment 'id 标识列',
user_name varchar(12) not null comment '用户名',
password varchar(15) not null comment '密码',
address varchar(120) comment '地址'
)
这里要注意的是,给表赋值时单引号中什么都不写是可以赋值的,它和null是有区别的:
insert into student (id,user_name,password,address) values ('www','','','null');
只有null和什么数据都不传入才会受not null约束。
3.default
default是默认修饰符,用于在字段后面设置如果不传入数据时该字段的默认值:
create table student(
id char(36) comment 'id 标识列',
user_name varchar(12) not null comment '用户名',
password varchar(15) not null comment '密码',
address varchar(120) default '中国' comment '地址'
)
insert into student (id,user_name,password) values ('www','','');
select * from student;
4.unique
unique修饰符代表该字段的数据是不允许重复的:
create table student(
id char(36) comment 'id 标识列',
user_name varchar(12) unique not null comment '用户名',
password varchar(15) not null comment '密码',
address varchar(120) default '中国' comment '地址'
)
5.primary key
主键,要说作用,该字段不能为null且不允许重复,是not null和unique的作用的结合,但它更大的用处还是作为一种标志,标志着该字段是这张表具有代表性的字段:
create table student(
id char(36) primary key comment 'id 标识列',
user_name varchar(12) unique not null comment '用户名',
password varchar(15) not null comment '密码',
address varchar(120) default '中国' comment '地址'
)
6.外键
详情见博客:MySQL数据库为什么要使用外键