1. 程式人生 > >day05-表的三種關係

day05-表的三種關係

表的三種關係

1)一對一

關聯方式:foreign key+unique
例如1個學生只能有1個學號,1個學號只能對應1個學生

#兩張表: 學生表(student)和 學號表(student_id)
# 建立學生表
create table student(
    id int primary key auto_increment,
    name varchar(20)
);
# 建立學號表
create table student_id(
    id int primary key auto_increment,
    url varchar(100),
    user_id int unique,
    constraint fk_student foreign key(id) references student(id)
    on delete cascade
    on update cascade

 

2)一對多(或多對一)

關聯方式:foreign key
例如書和出版社和關係,一個出版社可以出版多本書。

#創建出版社表
create table book_concern(
    id int primary key auto_increment,
    name varchar(20)
);
#建立圖書表
create table book(
    id int primary key auto_increment,
    name varchar(20),
    book_concern_id int not null,
    constraint fk_book_concern foreign key(id) references book_concern(id)
    on delete cascade
    on update cascade
);

 

3)多對多

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

# 建立被關聯表author表,之前的book表在講多對一的關係已建立
create table author(
    id int primary key auto_increment,
    name varchar(20)
);

#建立一張新的表,這張表存放了author表和book表的關係,查詢二者的關係只需查這張表就可以了
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 on update cascade, constraint fk_book foreign key(book_id) references book(id) on delete cascade on update cascade, primary key(author_id,book_id) );