1. 程式人生 > >mysql三表查詢sql語句

mysql三表查詢sql語句

  1. 表結構:

Student學生表(學號、姓名、性別、年齡、編輯)

Course課程表(編號、課程名稱)

sc選課表(選課編號、學號、課程編號、成績)

(1)寫一個SQL語句,查詢選修了“計算機原理”的學生學號和姓名

(2)寫一個SQL語句,查詢“小明”同學選修的課程名稱

(3)寫一個SQL語句,查詢選修了5門課程的學生學號和姓名

 

答案:

1

select student.stu_no,student.stu_name

from student,course,sc

where course.c_no=sc.c_no and sc.stu_no=student.stu_no and course.c_name='計算機原理

';

2

select course.c_name,student.stu_name

from student,course,sc

where student.stu_name='小明' and student.stu_no=sc.stu_no and sc.c_no=course.c_no;

3

select student.stu_no,stu_name

from student,course,sc

where student.stu_no=sc.stu_no and sc.c_no=course.c_no

group by student.stu_no

having count(*)=5

 

建表及插入資料可參考如下語句:

create table student(

stu_no int,

stu_name varchar(10),

sex char(1),

age int(3),

edit varchar(20)

);

 

insert into student values

(1,'wang','',21,'hello'),

(2,'小明','',22,'haha2'),

(3,'hu','',23,'haha3'),

(4,'li','',25,'haha4');

 

create table course(

c_no int,

c_name varchar(10)

);

 

insert into course values

(1,'計算機原理'),

(2,'java'),

(3,'c'),

(4,'php'),

(5,'py');

 

create table sc(

sc_no int,

stu_no int,

c_no int,

score int(3)

);

 

insert into sc values

(1,1,1,80),

(2,2,2,90),

(3,2,1,85),

(4,2,3,70),

(5,2,4,95),

(6,2,5,89);