您好,登錄后才能下訂單哦!
這篇文章主要介紹“MySQL如何創(chuàng)建多對多和一對一關(guān)系”,在日常操作中,相信很多人在MySQL如何創(chuàng)建多對多和一對一關(guān)系問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”MySQL如何創(chuàng)建多對多和一對一關(guān)系”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
create table students ( id int not null primary key auto_increment, name varchar(45) not null )engine=innodb default charset=utf8;
create table courses ( id int not null primary key auto_increment, name varchar(45) not null )engine=innodb default charset=utf8;
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;
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,"數(shù)學(xué)"); 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);
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;
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;
創(chuàng)建用戶表:
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;
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);
查詢?nèi)说娜啃畔ⅲ?/strong>
select * from users inner join users_info on users_info.user_id =users.id;
到此,關(guān)于“MySQL如何創(chuàng)建多對多和一對一關(guān)系”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。