明月清风精进不止 2020-04-21
分组查询
分组查询语句:
SELECT …… FROM <表名> WHERE …… GROUP BY ……
eg:
SELECT COUNT(*) AS 人数, SGrade AS 年级 FROM Students GROUP BY SGrade
多列分组:
SELECT COUNT(*)........FROM 表名 COUNT BY 列名 ORDER BY 想要按照排列的列名
eg:
SELECT COUNT(*) AS 人数,SGrade AS 年级,SSex AS 性别 FROM StudentS GROUP BY SGrade,SSex ORDER BY SGrade
分组筛选语句:
语法:
SELECT …… FROM <表名> WHERE …… GROUP BY …… HAVING……
eg:
SELECT COUNT(*) AS 人数,SGrade AS 年级 FROM Students GROUP BY SGrade HAVING COUNT(*)>15
WHERE与HAVING对比:
WHERE子句 用来筛选 FROM 子句中指定的操作所产生的行 GROUP BY子句 用来分组 WHERE 子句的输出 HAVING子句 用来从分组的结果中筛选行
内连接(INNER JOIN)
内连接使用比较运算符根据每个表的通用列中的值匹配两个表中的行
内连接语句:
SELECT …… FROM 表1 INNER JOIN 表2 ON ……
等价于
SELECT …… FROM 表1,表2 WHERE ……
eg:
SELECT Students.SName, Score.CourseID, Score.Score FROM Students,Score WHERE Students.SCode = Score.StudentID
左连接:(LEFT JOIN)
eg:
SELECT S.SName,C.CourseID,C.Score FROM Students AS S LEFT JOIN Score AS C ON C.StudentID = S.SCode
右连接:(RIGHT JOIN )
eg:
SELECT 图书编号,图书名称,出版社名称 FROM 图书表 RIGHT JOIN 出版社表 ON 图书表.出版社编号 = 出版社表.出版社编号