首頁 >資料庫 >mysql教程 >MySQL如何創造多對多和一對一關係

MySQL如何創造多對多和一對一關係

WBOY
WBOY轉載
2023-05-26 22:55:191991瀏覽

一、建立多對多

1.學生表

create table students (
  
id int not null primary key auto_increment,
  
name varchar(45) not null
  
)engine=innodb default charset=utf8;

2.課程表

create table courses (
  
id int not null primary key auto_increment,
  
name varchar(45) not null 
  
)engine=innodb default charset=utf8;

3.中間表

create table stu_cour (
  
id int not null primary key auto_increment
  
course_id int not null,
  
stu_id int not null,
  
constraint cour foreign key(course_id) references courses(id),
  
constraint stu foreign key(stu_id) references students(id)
  
)engine=innodb default charset=utf8;

4.插入資料

insert into students values (0,"小王");
insert into students values (0,"小宋");
insert into students values (0,"小李");


insert into courses values (0,"语文");
insert into courses values (0,"数学");
insert into courses values (0,"英语");


insert into stu_cour values (0,1,1);
insert into stu_cour values (0,1,2);
insert into stu_cour values (0,1,3);
insert into stu_cour values (0,2,1);
insert into stu_cour values (0,2,3);
insert into stu_cour values (0,3,2);
insert into stu_cour values (0,3,3);

5.查詢學生1選了哪些科目

SELECT courses.id,courses.name FROM courses 

INNER JOIN stu_cour ON stu_cour.course_id=courses.id

INNER JOIN students ON students.id= 1 

and students.id = stu_cour.stu_id;

MySQL如何創造多對多和一對一關係

#6.查詢id=2數學被誰選了

SELECT students.name FROM students 

INNER JOIN stu_cour ON stu_cour.stu_id =students.id

INNER JOIN courses ON courses.id= 2 

and stu_cour.course_id = courses.id;

MySQL如何創造多對多和一對一關係

 二、MySQL 建立一對一關係

1.一對一

建立使用者表:

CREATE TABLE users (

id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(50) NOT NULL

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

使用者資訊表:

CREATE TABLE users_info (

id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,

age int NOT NULL,

phone varchar(11) NOT NULL,

user_id int not null,
constraint user_info foreign key(user_id) references users(id)

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.插入資料

insert into users values (0,"小王");
insert into users values (0,"小宋");


insert into users_info values (0,12,'13812345678',1);
insert into users_info values (0,14,'13812345679',2);

查詢人的完整資訊:

select * from users inner join users_info on
users_info.user_id =users.id;

以上是MySQL如何創造多對多和一對一關係的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除