Mysql主键外键操作

外键:

·一对多

·多对多

·一对一

·修改表

·复制表

 

主键:

 

rimary key auto_increment(primary key是主键通常和auto_increment自动增加混合使用)

把所有数据存放到一张表中的弊端:

  1. 组织结构不清晰
  2. 浪费硬盘空间
  3. 扩展性差

一对多

create table school(
id int primary key auto_increment,    #primary key设置主键
school_name char(60)
);
create table class(
id int primary key auto_increment,
class_name char(40),
school_id int,
foreign key(school_id) references school(id)    #设置外键
on update cascade    #允许数据更新
on delete cascade    #允许数据删除
);

insert into school(school_name) values
('上海虹桥校区'),
('上海康桥校区');
insert into class(class_name,school_id) values
('python1班',1),
('python2班',2),
('python3班',1);

 

删除数据:

mysql> delete from school where id=2;

删除数据后school中的id字段为2的数据和class表中school_id字段为2的数据都会删除掉。

 

更新数据:

mysql> update school set id=3 where school='上海虹桥校区';

更新主键school中的id数据后,应为和class主外键绑定,外键class中的school_id字段也进行更新。

 

多对多

针对多对多这样的情况不能直接进行两个表关系绑定,不论怎么创建都会报错,新增一张表,这个表来进行两个表的关系绑定

图书表与作者表之间的关系
在两张表的角度:
1、在图书的角度:一本书可以对应一个作者也可以对应多个作者
2、在作者角度:一个作者可以写多本书
双方都能根据一条数据记录对应对方多条记录,这种关系就是多对多
面对这种双方相互对应没有办法直接建立关系,解决办法是另外建立一张关系表
create table author(
id int primary key auto_increment,
name char(16)
);
create table book(
id int primary key auto_increment,
book_name char(16),
price int
);
insert into author(name) values('egon'),('alex'),('xxx');

insert into book(book_name,price) values('python',20000),
('降龙十八掌',99.99),
('葵花宝典',9.9),
('九阴真经',8.8);

create table author_to_book(
id int primary key auto_increment,
author_id int,
book_id int,
foreign key(author_id) references author(id)
on update cascade
on delete cascade,
foreign key(book_id) references book(id)
on update cascade
on delete cascade
);

insert into author_to_book(author_id,book_id) values
(1,3),
(1,4),
(2,1),
(2,3),
(2,4),
(3,4);

#一对一
一张表强制拆分成为了两张表
create table customer(
id int primary key auto_increment,
name char(20) not null,
qq char(10) not null,
phone char(11) not null default '11111111111'
);
create table student(
id int primary key auto_increment,
class_name char(20) not null,
customer_id int unique, #该字段唯一
foreign key(customer_id) references customer(id)
on delete cascade
on update cascade
);

insert into customer(name,qq,phone) values
('egon','107170955','13579035789'),
('own','107170966','13579035469'),
('xxx','100000000','13333035789'),
('tank','106171955','13579035789')
;
insert into student(class_name,customer_id) values
('语文','1'),
('数学','2'),
('英语','3'),
('地理','4');

 

猜你喜欢

转载自www.cnblogs.com/yangzhaon/p/10863952.html
今日推荐