mysql 外來鍵 foreign key 一對一 一對多 多對多 約束
阿新 • • 發佈:2022-05-05
-- 建立書名錶 CREATE TABLE tb_books( id int primary key auto_increment, name varchar(24) not null comment "書籍名稱", isbn varchar(15) not null comment "編號" ); -- 插入書名 INSERT INTO tb_books(name, isbn) values ("夢裡花落知多少", '9787102832855'), ("盜墓筆記", '9787102885255'), ("我不", '9787102859865'), ("你猜",'9787102896745'); -- 建立作者表 CREATE TABLE tb_author( id int primary key auto_increment, name varchar(12) not null comment "作者" ); -- 插入作者 INSERT INTO tb_author(name) values ("三毛"), ("南派三叔"), ("大冰"); -- 建立關係表 CREATE TABLE tb_book_author( id int primary key auto_increment, book_id int, author_id int, foreign key(book_id) references tb_books(id) ON update cascade ON DELETE cascade, foreign key(author_id) references tb_author(id) ON DELETE cascade ON update cascade ); -- 插入關係 insert into tb_book_author(book_id, author_id) values(1, 1), (2, 2), (3, 3), (4, 3);
上面僅僅演示了 多對多的情況, 無非就是通過中間表來繫結雙方的關係
一對一, 一對多, 只需要在使用率較高的一張表上 建立外來鍵 並使用 unique 即可