mysql帶條件查詢,聯表查詢


 

---恢復內容開始---

1,用於設定所select出來的數據是否允許出現重復行(完全相同的數據行)

all:允許出現——默認不寫就是All(允許的)。

distinct:不允許出現——就是所謂的“消除重復行”

 

2,where:條件

 

3,group by:分組依據 后面加表的字段名,通常只進行一個字段的分組

mysql表查詢語法形式:select [all | distinct] 字段名或表達式 from 表名 [where] [group by] [having] [order by] [limit];

練習題:共有下面四張表    學生表:student  教師表:teacher  課程表:course 成績表:score

 

1,查詢Score表中至少有5名學生選修的並以3開頭的課程的平均分數

--操作表score,以cno分組並且cno是以3開頭,取出各個cno的總數,及與cno對應的degree的平均值

select count(cno),avg(degree) from score where cno like '3%' group by cno;

 

 

--從虛擬表中找到cno總數大於5的

select * from

(select count(cno) a,avg(degree) b from score where cno like '3%' group by cno) c

where a>5;

 

2,查詢所有學生的Sno、Cname和Degree列

--找到student的sno
 select sno from student;


 --找到score 的sno,degree,cno
 select sno,degree,cno from score;


 --找到course的cno
 select cno,cname from course;


 --組成新表cno sno degree
 select a.cno,b.sno,b.sname,a.degree from (select sno,degree,cno from score) a  join (select sno,sname from student) b on a.sno=b.sno;


 --組成有cname cno sn degree sname的表
 select d.cname,e.cno,e.sno,e.degree,e.sname
 from
   (select a.cno,b.sno,b.sname,a.degree from (select sno,degree,cno from score) a  join (select sno,sname from student) b on a.sno=b.sno) as e 
  join 
  (select cname,cno from course) as d
  on d.cno=e.cno;

 

3,查詢“95033”班學生的平均分

--從student取sno class,條件是class是95033的

select sno,class from student where class='95033';

 

--取出score中sno degree

select sno,degree from score;

 

--將上面兩張表組成一張,取degree的平均值

select avg(degree) from

(select sno,class from student where class='95033') a

join

(select sno,degree from score) b

on a.sno=b.sno;

 

4,查詢選修“3-105”課程的成績高於“109”號同學成績的所有同學的記錄

--將109號的成績取出

select degree from score where sno='109' and cno='3-105';

 

-- 得出最終表

select * from score

where

degree>(select degree from score where sno='109' and cno='3-105')

and cno='3-105';

 

5,查詢和學號為108的同學同年出生的所有學生的Sno、Sname和Sbirthday列

--找到student中sno為108 的Sbirthday
select year(sbirthday) from student where sno='108';


-- 得出最終表
select sno,sname,sbirthday from student

where

year(sbirthday)=(select year(sbirthday) from student where sno='108');


免責聲明!

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



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