1.主键
什么是主键
主键是能确定一条记录的唯一标识。比如:一条记录包括身份正号,姓名,年龄。身份证号是唯一能确定你这个人的,其他都可能有重复,所以身份证号是主键。声明主键的方法
不设置主键1
2
3
4mysql> CREATE TABLE t1(
id int not null,
name char(20)
);
带主键的
1
2
3
4mysql> CREATE TABLE t1(
id int not null primary key,
name char(20)
);
复合主键
1
2
3
4
5
6
7
8
9
10
11
12
13
14mysql> CREATE TABLE t1(
id int not null,
name char(20),
primary key (id,name)
);
```
主键自增的
```mysql
mysql> create table dd(
id int primary key not null auto_increment,
name varchar(20),
time timestamp default current_timestamp
);
创建完后再决定主键
1
2
3
4
5
6
7mysql> create table t(
id int not null,
name varchar(200) not null,
time timestamp default current_timestamp
);
mysql> alter table t add primary key (id);
mysql> alter table t drop primary key (id);
2.外键
什么是外键
一张表中有一个非主键的字段指向了别一张表中的主键,该字段叫做外键。
一张表中可以有多个外键。外键作用
对子表(外键所在的表)的作用:子表在进行写操作的时候,如果外键字段在父表中找不到对应的匹配,操作就会失败。
对父表的作用:对父表的主键字段进行删和改时,如果对应的主键在子表中被引用,操作就会失败。外键条件
表储存引擎必须是innodb,否则创建的外键无约束效果。
外键的列类型必须与父表的主键类型完全一致。
外键的名字不能重复。
已经存在数据的字段被设为外键时,必须保证字段中的数据与父表的主键数据对应起来。新增外键
在创建时增加1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16mysql> create table province(
pId int primary key auto_increment,
pName varchar(20)
);
mysql> create table user(
userId int primary key auto_increment,
userName varchar(40),
pid int,
foreign key(pid) references province(pId)
);
mysql> create table city(
cityId int primary key auto_increment,
cName varchar(20)
);在创建好的表中增加
1
2
3
4
5mysql> alter table user add cityId int;
mysql> alter table user add foreign key(cityId) references city(cityId);
mysql> alter table city add pid int;
mysql> alter table city add foreign key(pid) references province(pId);
- 删除外键
1
mysql> alter table tablename drop foreign key 外键名字;