1.PK(主键约束)
在关系数据库一个表中只能有一个主键(Primary Key),有写数据库没有PK,系统不出错误。在mysqk数据库建立表时,可以有主键,也可以没有(建议建表时有主键)。
主键列在插入数据时,必须填写,不能为null,不能重复。
-- 建立表 使用主键
create table tt1(
t int primary key
);
create table tt2(
t int,
primary key(t)
);
create table tt3(
t int unsigned auto_increment primary key
);
create table tt4(
t char(5)
);
insert tt4 values(1),(2),(2),(3),(2),(5);
select * from tt4;
-- 有重复数据,将不法增加主键约束
alter table tt4 add primary key(t);
-- 删除主键
alter table tt4 drop primary key;
-- 建立复合主键,此表还是只有一个主键,在系统数据库mysql.user表中的复合主键。
create table tt5(
id int unsigned,
name varchar(30) not null,
age tinyint unsigned default 18,
primary key(id,name)
);
-- 表约束
-- 主键PK约束(索引)唯一约束 非空 默认值
show tables;
create table wx_student(
sno char(6) primary key,/*主键 PK 不能空,不能重复,一个表只有有一个主键*/
sname varchar(30) not null,
sphone char(11) unique ,/*唯一约束,不能重复*/
sage tinyint unsigned default 18,
saddr varchar(255),
key(sname)
);
-- 定义uuid自动主键
create table ws_goods(
id char(36) default (uuid()) primary key,
name varchar(50) not null,
price decimal(10,1)
);
insert into ws_goods(name,price) values(uuid(),'笔记本',3000),('台式机',5500);
insert into ws_goods(id,name,price) values(uuid(),'服装',260),(uuid(),'台式机2',3500);
select * from ws_goods;
select uuid_short(),uuid();
create table t2(t bigint unsigned);
drop table t2;
-- 99657422712340480
insert into t2 value(99657422712340480);
select uuid_short(),uuid_short(),uuid_short(),uuid_short();
2.FK(外键约束)
Fk foreign key 外键约束,一般设计多个表,关联约束形式,在mysql,表的存储引擎为innodb时才可以使用外键。
-- 外键约束
show engines;
-- 默认的存储引擎为InnoDB 支持事务 外键 行级锁
-- 建立老师表
create table teacher(
id int UNSIGNED auto_increment, /*PK*/
name varchar(10) not null,
primary key(id)
);
insert teacher(name) values('李老师'),('赵老师'),('张老师'),('周老师');
alter table student add constraint sfk foreign key(tid) REFERENCES teacher(id) on delete cascade on update cascade;
alter table student drop constraint sfk;
alter table student add constraint sfk foreign key(tid) REFERENCES teacher(id) on delete set null on update cascade;
insert into student values(10,'李四',1),(15,'李丽',2),(22,'张三丰',1);
此代码通过外键将学生与老师联系在一起,学生的tid就是老师的id。
3.unique 唯一约束,not null和default
create table stu(
id int unsigned auto_increment,
name varchar(15) unique,/*唯一约束,可以不填写,如果填写,不能重复*/
age tinyint unsigned default 18,/*默认值18*/
gender enum('男','女') default '男',
address varchar(255) not null,/*必须写*/
primary key(id)
)