數據庫中多對多的關系


數據庫中的關系有一對一、一對多、多對多三種。

  • 一對一很好理解了。
  • 一對多,例如員工與部門的關系,一個員工只能屬於一個部門,一個部門擁有多名員工,類似這樣判斷結果的都是一對多,沒有多對一的關系。
  • 多對多, 學生與老師的關系,一個老師教很多學生,一個學生有不同科目的老師。

主要看看一對多關系和多對多。建立如下表:

  • 一對多:
create table employee(
id int auto_increment,
name varchar(20) not null,
dep_id int not null,
primary key(id)
);
insert into employee (name,dep_id) values ("劉備",1),("張飛",2),("關羽",2)

create table department (
id int auto_increment,
name varchar(20),
primary key(id)
);
insert into department (name) values("總經辦"),("市場部");
alter table employee add foreign key (dep_id) references department (id);//插入外鍵

使用內部聯結查詢:

select e.id,e.name,d.name from employee e inner join department d on e.dep_id=d.id;

查詢結果:

  • 多對多的表的設計:
create table student(
id int auto_increment,
name varchar(20) not null,
primary key(id)
);
insert into student (name) values("張三"),("李四"),("王五"),("趙六")

 

create table teacher(
id int auto_increment,
name varchar(20) not null,
primary key(id)
);
insert into teacher (name) values("趙四"),("李武"),("王九"),("劉師");

 

create table relation(
stu_id int not null,
tea_id int not null
);
insert into relation (stu_id,tea_id) values (1,1),(1,2),(1,3),(2,2),(2,3),(3,2),(4,1),(4,2);
//添加外鍵
alter table relation add foreign key(stu_id) references student (id);
alter table relation add foreign key(tea_id) references teacher (id);

查看每個學生都選了哪些老師:

select s.name ,t.name from 
student s inner join relation r 
on s.id=r.stu_id inner join teacher t
on t.id=r.tea_id

這樣看,不太美觀,采用分組的形式,並顯示組內的詳細內容:

select s.name ,group_concat(t.name) from 
student s inner join relation r 
on s.id=r.stu_id inner join teacher t
on t.id=r.tea_id
group by s.name;

查詢成功!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM