对于多对多关系的对象,如何建表与关联查询(转载)
(一)背景介紹
??在數(shù)據(jù)庫中建表時,很容易遇到一種情況:一個學生選修了多門課,而每門課有多名學生選修,“學生”和“課程”之間就是典型的多對多關系。
(二)如何建表
??遇到這種多對多關系,我們一般是創(chuàng)建三張表:Student(學生表)、Course(課程表)和選課表(id、student_id、course_id)
?
下面來自狗書
?
查詢多對多關系要分成兩步。
若想知道某位學生選擇了哪些課程,
students中根據(jù)name獲取id
registrations中根據(jù)id獲取所有他選擇的課程的id
classes中根據(jù)課程的id得到課程名字
#------------------------------------------------------------
同樣,若想找到選擇了某門課程的所有學生,
classes中根據(jù)課程的名字得到id
registrations中根據(jù)id獲取所有選擇這門課程的學生的id
students列表中根據(jù)所有選擇這門課學生的id,獲得所有學生的名字
#------------------------------------------------------------
光說不夠,下面是具體的實踐.
--------------------------------------------------------datagrip建表--------------------------------------------------------
學生表建立:
CREATE TABLE students
(
? ? id int PRIMARY KEY AUTO_INCREMENT,
? ? name varchar(64),
? ? date time
);
中間表建立:
CREATE TABLE temp
(
? ? student_id int,
? ? curriculum_id int
);
課程表建立:
CREATE TABLE curriculums
(
? ? id int PRIMARY KEY AUTO_INCREMENT,
? ? name varchar(32),
? ? date time,
? ? status varchar(8)
);
---------------------------------下面是插入數(shù)據(jù)-----------------------------------------------------------
students:
?
temp:
?
curriculums:
?
------------------------------下面是關聯(lián)語句查詢--------------------------------------------------------
小白兔選擇的所有課程:
mysql>SELECT curriculums.name FROM curriculums?
INNER JOIN temp ON temp.curriculum_id=curriculums.id?
INNER JOIN students ON students.name="小白兔" and students.id = temp.student_id;
+-----------------+
| name ? ? ? ? ? ?|
+-----------------+
| 數(shù)據(jù)庫設計 ? ? ?|
| 計算機原理 ? ? ?|
| 大學物理 ? ? ? ?|
+-----------------+
選中"數(shù)據(jù)庫設計"課程的所有人:
mysql>select students.name from students?
inner join temp on temp.student_id=students.id?
inner join curriculums on curriculums.name="數(shù)據(jù)庫設計" and curriculums.id=temp.curriculum_id;
+-----------+
| name ? ? ?|
+-----------+
| 小白兔 ? ?|
| 大森林 ? ?|
+-----------+
?
總結
以上是生活随笔為你收集整理的对于多对多关系的对象,如何建表与关联查询(转载)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL性能优化之char、varch
- 下一篇: 淘宝Django书籍调研