第一种:创建表的时候
create table table_name(
列名1 数据类型 (int) primary key auto_increment,
列名2 数据类型 not null,
列名3 数据类型 unique,
列名4 数据类型 default '值',
constraint 索引名 foreign key(外键列) references 主键表(主键列)
on delete cascade | on delete set null
)
--举例:
create table if not exists student(
id int primary key auto_increment,
name varchar(50) unique,
age int not null,
sex varchar(10) default '男'
)default charset = utf8;
第二种:建表完成之后
create table if not exists student(
id int,
name varchar(50),
age int,
sex varchar(10)
)default charset = utf8;
1.非空约束
--添加:alter table [表名] modify [列名] 数据类型 not null
--删除:alter table [表名] modify [列名] 数据类型 null
mysql> alter table student modify name varchar(30) not null;
mysql> alter table student modify name varchar(30) null;
2.唯一约束
--添加:alter table [表名] add unique 约束名(字段)
mysql> alter table student add unique(age);
mysql> alter table student add unique gender(sex);
--删除:alter table [表名] drop key 约束名
mysql> alter table student drop key age;
mysql> alter table student drop key gender;
mysql> alter table student drop index age;
--查看约束名:
mysql> show create table student;
3.主键约束
4.自动增长
5.外键约束
--添加:alter table table_name add constraint 约束名 foreign key(外键列) references 主键表(主键列)
--删除:
--第一步:删除外键
mysql> alter table table_name drop foreign key 约束名
--第二步:删除索引(约束名和索引名一样)
mysql> alter table table_name drop index 索引名
6.默认值
--添加:alter table [表名] alter 列名 set default '值'
--删除:alter table [表名] alter 列名 drop default
--修改:alter table [表名] alter 列名 set default '值'
mysql> alter table student alter name set default "liu";
mysql> alter table student alter name drop default;
mysql> alter table student alter name set default "hai";
/*有时无法直接修改默认值,则:
1.先把此列删掉,然后再增加,增加的时候直接把默认值附上。
alter table tablename drop column cloumnname;
alter table tablename add column columnname timestamp default value;
2.删掉表,重新建表。在建表时设置默认值。*/
附加: MySQL数据表中有自增长主键时如何插入数据
--MySQL数据库表中有自增长主键ID时,当用SQL插入语句中插入语句带有ID列值记录的时候:
--1.如果指定了该列的值,则新插入的值不能和已有的值重复,而且必须大于其中最大的一个值;
mysql> insert into student values(2,'hai',25,'男');
--2.也可以不指定该列的值,只将其他列的值插入,让ID还是按照MySQL自增自己填;这种情况在进行插入的时候,两种解决方法:
--①可以把id的值设置为null或者0,这样子mysql都会自己做处理
mysql> insert into student values(null, 'mmm', 26, '女');
mysql> insert into student values(0, 'nnn', 25, '男');
--②手动指定需要插入的列,不插入这一个字段的数据!
mysql> insert into student(name,age,sex) values('xxx',30,'男');
--参考:https://blog.csdn.net/J080624/article/details/71703297
https://blog.csdn.net/qq_36855487/article/details/82945567