sql多表查詢--學生課程表查詢


創建表

學生表:(序號,姓名,年齡,專業)

create table s(
sno INT(11) auto_increment,
sname varchar(125),
sage INT(11),
sdept varchar(125),
primary key(sno)
);

 課程表:(序號,課程名)

create table c(
cno INT(11) auto_increment,
cname varchar(255),
primary key(cno)
);

 學生課程關系表:(序號,學生序號,課程序號,分數)

create table sc(
scno INT(11) auto_increment,
sno INT(11),
cno INT(11),
grade INT(255),
primary key(scno)
);

 

常用單表查詢

limit

一個參數是查詢條數

select sno,sname from s limit 2

 

兩個參數n,m是(1.從第n+1行開始2.查詢m條數)

select sno,sname from s limit 0,2

 

between

select  sno,sname,sage from s where sage between 18 and 20

 

 distinct

 不重復查詢

select distinct sdept from s 

 

like

通配符查詢

select  sname from s where sname like "小%"

 

 

 

多表查詢

in

 1.查詢修讀“軟件工程”的學生姓名(使用in嵌套子查詢)

select sname from s where sno in
(select sno from sc where cno in (
	select cno from c where cname="軟件工程"
))

 2.查詢至少修讀“軟件工程”與“c語言”的學生姓名(在1中使用or)

select sname from s where sno in 
(select sno from sc where cno in 
(select cno from c where cname="軟件工程" or cname="c語言")) 

 3.查詢不修“軟件工程”的學生姓名(在2中使用not)

select sname from s where sno in 
(select sno from sc where cno not in 
(select cno from c where cname="軟件工程" )) 

 exits


免責聲明!

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



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