1. 程式人生 > >Mysql主鍵外鍵操作

Mysql主鍵外鍵操作

mysq 角度 硬盤空間 customer 作者 pda 圖書 一個 family

外鍵:

·一對多

·多對多

·一對一

·修改表

·復制表

?

主鍵:

?

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‘);

?

Mysql主鍵外鍵操作