SQL 学习笔记
Archived University Note
This content is from my university archives and may not be reliable or up-to-date.
SQL 学习笔记
基础查询
-- 查询指定列
select sno,sn,age from s
select * from sc
-- 列别名
select sn name, sno,age from s
条件查询
-- 简单条件
select SNo,score from sc where cno='c1'
select sno,cno,score from sc where score > 85
-- 复合条件
select SNo,score from sc where (cno='c1' or cno='c2') and score > 85
范围查询与模式匹配
-- BETWEEN 范围查询
select tno,tn,prof from t where sal between 1000 and 1500
select tno,tn,prof from t where sal not between 1000 and 1500
-- LIKE 模式匹配
select tno,tn from t where tn like '张%' -- 以'张'开头
select tno,tn from t where tn like '%' -- 包含任意字符
select tno,tn from t where tn like '_雪' -- 第二个字是'雪'
聚合函数
-- 常用聚合函数:avg() sum() max() min() count()
select sum(score) as totalscore, avg(score) as avgscore
from sc where sno='s1'
-- 计算最高分、最低分和分数差
select max(score) as MaxScore, min(score) as MinScore, Max(Score)-Min(Score) as diff
from sc where (cno='c1')
-- 统计记录数
select count(*) from s where dept='计算机'
-- distinct 消除重复行(count对null不计算,对0计算)
select count(distinct dept) as deptnum from s
分组查询
-- GROUP BY 分组
select tno, count(*) as C_Num from tc Group by tno
-- HAVING 过滤分组
select Sno, count(*) as sc_num from sc group by sno having (count(*) >= 2)