1.在查詢結果中顯示列名:
a.用as關鍵字:select name as '姓名' from students order by age
b.直接表示:select name '姓名' from students order by age
2.精確查找:
a.用in限定范圍:select * from students where native in ('湖南', '四川')
b.between...and:select * from students where age between 20 and 30
c.“=”:select * from students where name = '李山'
d.like:select * from students where name like '李%' (注意查詢條件中有“%”,則說明是部分匹配,而且還有先後信息在裡面,即查找以“李”開頭的匹配項。所以若查詢有“李”的所有對象,應該命令:'%李%';若是第二個字為李,則應為'_李%'或'_李'或'_李_'。)
e.[]匹配檢查符:select * from courses where cno like '[AC]%' (表示或的關系,與"in(...)"類似,而且"[]"可以表示范圍,如:select * from courses where cno like '[A-C]%')
3.對於時間類型變量的處理
a.smalldatetime:直接按照字符串處理的方式進行處理,例如:
select * from students where birth > = '1980-1-1' and birth <= '1980-12-31'
4.集函數
a.count()求和,如:select count(*) from students (求學生總人數)
b.avg(列)求平均,如:select avg(mark) from grades where cno=’B2’
c.max(列)和min(列),求最大與最小
5.分組group
常用於統計時,如分組查總數:
select gender,count(sno)
from students
group by gender
(查看男女學生各有多少)
注意:從哪種角度分組就從哪列"group by"
對於多重分組,只需將分組規則羅列。比如查詢各屆各專業的男女同學人數 ,那麼分組規則有:屆別(grade)、專業(mno)和性別(gender),所以有"group by grade, mno, gender"
select grade, mno, gender, count(*)
from students
group by grade, mno, gender
通常group還和having聯用,比如查詢1門課以上不及格的學生,則按學號(sno)分類有:
select sno,count(*) from grades
where mark<60
group by sno
having count(*)>1
6.UNION聯合
合並查詢結果,如:
SELECT * FROM students
WHERE name like ‘張%’
UNION [ALL]
SELECT * FROM students
WHERE name like ‘李%’
7.多表查詢
a.內連接
select g.sno,s.name,c.coursename
from grades g JOIN students s ON g.sno=s.sno
JOIN courses c ON g.cno=c.cno
(注意可以引用別名)
b.外連接
b1.左連接
select courses.cno,max(coursename),count(sno)
from courses LEFT JOIN grades ON courses.cno=grades.cno
group by courses.cno
左連接特點:顯示全部左邊表中的所有項目,即使其中有些項中的數據未填寫完全。
左外連接返回那些存在於左表而右表中卻沒有的行,再加上內連接的行。
b2.右連接
與左連接類似
b3.全連接
select sno,name,major
from students FULL JOIN majors ON students.mno=majors.mno
兩邊表中的內容全部顯示