Mysql-表關系


表關系分為三種:一對一,一對多,多對多

 

一對多:一個學院對應多個學生,而一個學生只對應一個學院  

--  這兒classroom 是代表的學院。

-- 一對多 - A表的一條記錄 對應 B 表多條記錄,B表一條記錄 只能對應 A表一條記錄
-- 一個classroom對應多個student
-- 創建主表
create table if not exists classroom(
    id int primary key auto_increment,
    name varchar(20)
);
-- 創建子表
create table student(
    id int primary key auto_increment,
    name varchar(10),
    cls_id int,
    constraint `idx_cls_id` foreign key(cls_id) references classroom(id)
);

insert into classroom(name) values('Python學院'),('Web學院'),('Java學院');

insert into student(name,cls_id) values('Which',1);
insert into student(name,cls_id) values('Tuple',1);
insert into student(name,cls_id) values('Tom',3);
insert into student(name,cls_id) values('Tim',2);

-- select * from student;
+----+-------+--------+
| id | name  | cls_id |
+----+-------+--------+
|  1 | Which |      1 |
|  2 | Tuple  |      1  |
|  3 | Tom    |      3  |
|  4 | Tim     |      2  |
+----+-------+--------+

一對一:一個學生對應一個地址,一個地址也對應一個學生

-- 一對一 - A表的一條記錄一定只能對應B表一條記錄,B表的一條記錄一定只能對應A表一條記錄

-- 創建學生的地址表 學生和地址一對一關系
create table stu_address(
    id int primary key auto_increment,
    address varchar(10),
    constraint `idx_adrs_id` foreign key(id) references student(id)
);

insert into stu_address(address) values('地球'),('月球'),('Earth'),('Moon');
--在插入第五六條數據會失敗,應為上表student只有4個學生,id最多為4
insert into stu_address(address) values('Earth'),('Moon');

-- select * from stu_address;
+----+---------+
| id | address |
+----+---------+
|  1 | 地球    |
|  2 | 月球    |
|  3 | Earth   |
|  4 | Moon    |
+----+---------+

多對多:老師對應多個學生,學生也可以對應多個老師

-- 創建老師表
create table teacher(
    id int primary key auto_increment,
    name char(12) not null

);
insert into teacher(name) values('陳老師'),('郭老師'),('范老師'),('夏老師');

-- 創建老師學生中間表
create table stu_teacher(
    st_id int,
    te_id int,
    primary key(st_id,te_id),
    constraint `idx_st_id` foreign key(st_id) references student(id),
    constraint `idx_te_id` foreign key(te_id) references teacher(id)
);

insert into stu_teacher values(1,1),(1,2),(2,1),(1,3),(3,1);
-- select * from stu_teacher;
+-------+-------+
| st_id | te_id |
+-------+-------+
|     1 |     1 |
|     2 |     1 |
|     3 |     1 |
|     1 |     2 |
|     1 |     3 |
+-------+-------+

 


免責聲明!

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



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