·简单属性
·null
代表字段为空
·默认值
default
create table my_default(
name varchar(10) not null, --不能为空
age int default 18 --默认值改成18
)charset utf8;
insert into my_default values('jack',default);
·列描述
comment:注释
create table my_comment(
name varchar(10) not null comment'非空用户名',
pass varchar(50) not null comment'密码不能为空'
);
show create table my_comment; --只能用这个指令查看,desc 看不到
·主键
primary key,在一张表中,有且只有一个字段,里面的值具有唯一性。
·创建主键
1·随表创建
--直接在需要当作的主键字段之后增加primary key属性
create table my_key1(
username varchar(10) primary key
);
--在所有字段之后增加primary key选项
create table my_key2(
username varchar(10) ,
primary key(username)
);
2·表后增加
alter table 表名 add primary key(字段名);
·查看主键
desc 表名;
show create table 表名;
·删除主键
alter table 表名 drop primary key;
·复合主键
create table my_score(
student_no varchar(10),
course_no varchar(10),
score int not null,
primary key(student_no, course_no)
)
·主键约束
当前字段对应的数据不能为空
当前字段对应的数据不能有任何重复
·主键分类
业务主键:主键所在字段具有业务意义(学生ID,课程ID)
逻辑主键:自然增长的整型(应用广泛)
·自增长
当给定某个字段该属性之后,该列的数据在没有提供确定数据的时候,系统会根据之前已经存在的数据进行自动增加(只适用于数值)
·使用自增长
create table my_incre(
id int primary key auto_increment,
name varchar(10) not null comment '用户名',
pass varchar(50) not null comment '密码'
)charset utf8;
insert into my_incre values(null,'Tom','123456'); --id自动置为1
·修改自增长
一个表只能有一个自增长
alter table my_incre auto_increment = 10; --必须比原值大
·删除自增长
alter table my_auto modify id int; --修改自增长所在字段,不加auto属性就自动清除
·初始设置
auto_increment_increment 步长
auto_increment_offset 初始值
扫描二维码关注公众号,回复:
8964635 查看本文章
show variables like 'auto_increment%'; --查看以上两个值
·细节问题
删除数据时不会重置auto_increment,解决方案:
truncate 表名; --等于先drop 再create
·唯一键
unique key:用来保证对应的字段中的数据唯一的。允许数据为NULL,且可以有多个。
主键也可以但是一张表只能有一个主键,可以有多个唯一键。
·创建唯一键
同主键 可以用unique 代替unique key
·查看唯一键
show create table 表名;
系统会给唯一键一个名字,默认与字段名一致
·删除唯一键
alter table 表名 drop unique key; --错误语句,一个表允许存在多个唯一键
alter table 表名 drop index 唯一键名字;
没有修改唯一键这个功能
·复合唯一键
同主键
一般主键都是单一字段(逻辑主键),其他唯一性用唯一键来保证