1. 程式人生 > 實用技巧 >多表結構的建立與分析

多表結構的建立與分析

多表結構的建立與分析

如何找出兩張表之間的關係

分析步驟:
#1、先站在左表的角度去找
是否左表的多條記錄可以對應右表的一條記錄,如果是,則證明左表的一個欄位foreign key 右表一個欄位(通常是id)

#2、再站在右表的角度去找
是否右表的多條記錄可以對應左表的一條記錄,如果是,則證明右表的一個欄位foreign key 左表一個欄位(通常是id)

#3、總結:
#多對一:
如果只有步驟1成立,則是左表多對一右表
如果只有步驟2成立,則是右表多對一左表

#多對多
如果步驟1和2同時成立,則證明這兩張表時一個雙向的多對一,即多對多,需要定義一個這兩張表的關係表來專門存放二者的關係

#一對一:
如果1和2都不成立,而是左表的一條記錄唯一對應右表的一條記錄,反之亦然。這種情況很簡單,就是在左表foreign key右表的基礎上,將左表的外來鍵欄位設定成unique即可

建立表之間的關係

#一對多或稱為多對一
二張表:出版社,書

一對多(或多對一):一個出版社可以出版多本書

關聯方式:foreign key
create table press(
id int primary key auto_increment,
name varchar(20)
);
create table book(
id int primary key auto_increment,
name varchar(20),
    press_id int not null,
    foreign key(press_id) references press(id) on update cascade
);

insert into press(name) values
('北京工業地雷出版社'),('人民音樂出版社'),('智慧財產權出版社');
insert into book(name,press_id) values('九陽神功',1),('九陰真經',2),('白骨爪',2);

#多對多
三張表:出版社,作者資訊,書

多對多:一個作者可以寫多本書,一本書也可以有多個作者,雙向的一對多,即多對多
  
關聯方式:foreign key+一張新的表

create table author(
id int primary key auto_increment,
name varchar(20)
);
create table author2book(
id int not null unique auto_increment,
author_id int not null,
 book_id int not null,
 constraint fk_author foreign key(author_id) references author(id)
    on delete cascade,
 constraint fk_book foreign key(book_id) references book(id)
    on delete cascade,
 primary key(author_id,book_id)    
);
insert into author(name) values('egon'),('alex'),('yuanhao'),('wpq');
insert into author2book(author_id,book_id) values
(1,1),
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(2,1),
(2,6),
(3,4),
(3,5),
(3,6),
(4,1);

#一對一
兩張表:學生表和客戶表

一對一:一個學生是一個客戶

關聯方式:foreign key+unique
create table customer(
id int primary key auto_increment,
name varchar(20) not null,
qq varchar(20) not null,
phone char(16) not null
 );
create table student(
id int primary key auto_increment,
class_name varchar(20) not null,
customer_id int unique,
foreign key(customer_id) references customer(id)
    on update cascade
);
insert into customer(name,qq,phone) values
    ('韓蕾','31811231',13811341220),
    ('楊瀾','123123123',15213146809),
    ('翁惠天','283818181',1867141331),
    ('楊宗河','283818181',1851143312),
    ('袁承明','888818181',1861243314),
    ('袁清','112312312',18811431230);
insert into student(class_name,customer_id) values
    ('脫產1班',3),
    ('週末1期',4),
    ('週末1期',5);