1.语法:
create table 库名.表名(
字段名1 类型[(宽度)约束条件],
字段名2 类型[(宽度)约束条件],
字段名3 类型[(宽度)约束条件]
);
约束条件:是在数据类型之外对字段附加的额外限制
注意:
1.最后一个字段之后不能加逗号
2.在同一张表中,字段名不能相同
3.宽度和约束条件可选,字段名和类型是必须的
2.约束
1.常见约束
not null 非空 default 默认值 auto_increment 自增长 primary key 主键 非空且唯一
实例:
create table t1( id int primary key auto_increment, name varchar(16) not null, sex enum('male','female') not null default 'male' );
插入无特殊情况只需插入name
insert into t1(name) values ('dahai'), ('xiaohei'), ('xiaobai'); mysql> select * from t1; +----+---------+------+ | id | name | sex | +----+---------+------+ | 1 | dahai | male | | 2 | xiaohei | male | | 3 | xiaobai | male | +----+---------+------+
auto_increment(自己设置初始值)
create table t2( id int primary key auto_increment, name varchar(20) not null) auto_increment = 100; 插入数据 insert into t2(name) values ('dahai'), ('xiaohei'), ('xiaobai'); mysql> select * from t2; +-----+---------+ | id | name | +-----+---------+ | 100 | dahai | | 101 | xiaohei | | 102 | xiaobai | +---------+-----+
2.唯一约束
unique key
实例:
创建方式一
create table t3(id int unique); 创建方式二 create table t4( id int, unique key(id) );
2.2联合唯一(二者加起来是唯一)
create table t5( ip varchar(15), port int, unique(ip,port) );
站在约束的角度来看 primary key =not null unique
主键:
1.必须有且只有一个主键
2.通常是id字段被设置成主键
create table t6( id int primary key auto_increment );
联合主键(二者加起来是非空且唯一)
create table t7( x varchar(15), y int, primary key (x,y) );