mysql學習 表內連線查詢

2021-09-26 09:52:00 字數 1860 閱讀 6435

查詢兩個表中符合條件的共有記錄

內連線查詢效果圖:

內連線查詢語法格式:

select 字段 from 表1 inner join 表2 on 表1.欄位1 = 表2.欄位2;
說明:inner join 就是內連線查詢關鍵字;on 就是連線查詢條件

在這裡我們先建立三個表分別是:student學生表,course課程表,stu_cour選課表

create table student(

id int unsigned primary key auto_increment not null,

name varchar(20) not null comment '學生姓名'

);insert into student values(0,'諸葛亮'),(0,'虞姬'),(0,'孫尚香'),(0,'趙雲'),(0,'宮本武藏');

create table course(

id int unsigned primary key auto_increment not null,

name varchar(20) not null comment '課程名稱'

);insert into course values

(0,'語文'),

(0,'數學'),

(0,'英語'),

(0,'物理'),

(0,'化學'),

(0,'歷史'),

(0,'地理');

create table stu_cour(

stu_id int comment '學生id',

cour_id int comment '課程id',

primary key(stu_id,cour_id)

);insert into stu_cour values

(1,1),(1,2),(1,3),(1,4),

(2,1),(2,2),(2,3),(2,5),

(3,1),(3,2),(3,3),(3,7),

(4,1),(4,2),(4,3),(4,4),

(5,1),(5,2),(5,3),(5,5);

例1,查詢諸葛亮選了那些課程

select * from student as s inner join stu_cour as sc inner join course as c on s.id=sc.stu_id and sc.cour_id=c.id and s.name='諸葛亮';
例2,查詢選物理課程的學生有哪些

select * from student as s inner join stu_cour as sc inner join course as c on s.id=sc.stu_id and sc.cour_id=c.id and c.name='物理';
例3,查詢已經被選過的課程有哪些

select c.name from stu_cour as sc inner join course as c on sc.cour_id=c.id group by c.name;
例4,查詢還沒有被選過的課程有哪些

select name from course where name not in (select c.name from stu_cour as sc inner join course as c on sc.cour_id=c.id group by c.name);

Mysql連表查詢(內連線 外連線)

建立兩張 並分別插入資料 create table ifnot exists left table id int auto increment,age int,name varchar 20 primary key id engine innodb default charset utf8 auto...

mysql 內連線查詢

例7.46 在fruits表和suppliers表之間使用內連線查詢,查詢之前,檢視兩個表的結構,select suppliers.s id,s name,f name,f price from fruits suppliers where fruits.s id suppliers.s id 例7...

聯表查詢 內連線 外連線

1.說明 聯表查詢可實現兩個或多個表之間的連線查詢,一般用於有主外來鍵關係表之間的連查詢,這裡拿兩個有主外來鍵關係的表來舉例說明聯表查詢的使用。student表 其中classid為外來鍵 class表 2.內連線查詢 查詢出學生的所有資訊 select from student a,class b...