数据查询
单表查询
--01.选择表中若干列
SELECT Sid,Sname FROM Student--查询指定列SELECT * FROM Student--查询全部列SELECT Sid,2024-Sage AS 年龄 FROM Student--查询经过计算的列,并为列起别名--02.选择表中若干元组
SELECT DISTINCT Sage FROM Student--去掉查询结果的重复行--常用查询条件
--=,<,>,<=,>=,<> OR !=
--BETWEEN AND,NOT BETWEEN AND
--IN,NOT IN
--LIKE,NOT LIKE
--IS NULL,IS NOT NULL
--AND,ORSELECT Sname FROM StudentWHERE (Sdept='计算机系' OR Sdept='软件系') AND Sage<=20--确定范围,多重条件查询,AND优先级高于OR
--也可以成
SELECT Sname FROM StudentWHERE Sdept IN('计算机系','软件系') AND Sage<=20SELECT Sname FROM StudentWHERE Sage NOT BETWEEN 20 AND 24SELECT Sname FROM StudentWHERE Sdept IN('软件系','计算机系','大数据系')--与IN中某个常量值相等结果为TureSELECT Sname FROM StudentWHERE Sdept NOT IN('软件系','计算机系','大数据系')--与IN中某个常量值相等结果为False
--此句等价于
SELECT Sname FROM StudentWHERE Sdept!='软件系' AND Sdept!='计算机系'AND Sdept!='大数据系'--字符串匹配
--_:匹配任意一个字符
--%:匹配0个或多个字符
--[]:匹配[]中的任意一个字符。[a-b]表示连续字母匹配,[abcg]表示匹配a、b、c、g中任意一个
--[^]:不匹配[]中的任意一个字符。==NOT LIKESELECT * FROM StudentWHERE Sname LIKE '张%'--姓‘张’SELECT * FROM StudentWHERE Sname LIKE '[张刘李]%'--姓‘张’、姓‘刘、’姓‘李’,等价于ORSELECT * FROM StudentWHERE Sname LIKE '_[小]%'--第二个字是‘小’SELECT * FROM StudentWHERE RTRIM(Sname) LIKE '王_'--姓‘王’且只有两个字,去掉尾随空格(RTRIM函数)SELECT * FROM StudentWHERE Grade IS NULL--查询空值数据--03.对查询结果进行排序
SELECT * FROM StudentORDER BY Sage ASCSELECT * FROM StudentORDER BY Sdept,Grade DESC--系名升序排序,同一系年龄降序--04.聚合函数
SELECT COUNT(*) AS 选课门数,SUM(Grade) AS 总成绩,AVG(Grade) AS 平均分,MAX(Grade) AS 最高分,MIN(Grade) AS 最低分FROM SC WHERE Cno='100001'--05.查询结果分组统计
SELECT Sid,COUNT(*) AS 选课门数 FROM SCWHERE Ssex='女'GROUP BY Sdept--统计每个系的女生的选课情况人数SELECT Sdept,Ssex,COUNT(*) AS 人数,MAX(Sage) AS 最大年龄FROM StudentGROUP BY Sdept,SsexORDER BY SdeptSELECT Sno,COUNT(*) AS 选课门数,AVG(Grade) AS 平均成绩FROM SCGROUP BY SnoHAVING AVG(Grade)>=80--HAVING子句用于分组后的结果再进行筛选(=WHERE),但是用于组,通常和GROUP BY一起用SELECT Sdept,COUNT(*) FROM StudentWHERE Ssex='男'--先挑选出全部男生GROUP BY Sdept--按系排序,执行聚合函数HAVING COUNT(*)>=2--筛选满足条件的结果--注意执行效率
SELECT Sdept,COUNT(*) FROM StudentWHERE Sdept IN('计算机系','软件系')GROUP BY Sdept--参与分组的数据比较少,效率更高
--vs
~~SELECT Sdept,COUNT(*) FROM StudentGROUP BY SdeptHAVING Sdept IN('计算机系','软件系')~~