重新瞭解數據庫——排序、分頁和子查詢

select完整語法

group by、having、order by和limit都要按照select語句的語法順序來寫。

 

排序

語法:order by 字段 升序/降序;

  • 升序ASC
  • 降序DESC
--查詢結果按成績升序排序
select id,name,score 
from student
order by score ASC;

 

分頁

語法:limit 起始值,頁面的大小

--查詢結果按成績升序排序,每五個分頁
select id,name,score 
from student
order by score ASC
limit 0,5;

 

子查詢

語法:在where中嵌套一個子查詢語句

查詢課程爲高數並且成績大於80分的學生學號和姓名

使用子查詢:子查詢稍微難理解一點但是語法簡潔

select id,name from student where id in (
  select id from result where score>80 and subjectId = (
  select subjectId from subject where subjectName = '高數'
  )
)

使用聯表查詢:

select s.id name
from student s
inner join result r
on s.id = r.id
inner join subject sub
on r.id = sub.id
where score>80 and subjectName='高數';

 

分組和過濾

在使用了分組後的過濾中不能使用where,需要使用having,不過他們兩個效果是一樣的。

--查詢不同課程的平均分,最高分,平均分大於80(根據不同的課程分組)
select SubjectName,AVG(score) as 平均分,MAX(score)
from result r
inner join subject sub
on r.SubjectId = sub.SubjectId
group by r.SubjectId
having 平均分>80;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章