1 SELECT的基本用法
SELECT * FROM 表名
SELECT 列名,列名,... FROM 表名
定义列别名
SELECT 列名 AS 别名(或列名 别名) FROM 表名
按条件过滤(WHERE子句)
SELECT 列名 FROM 表名 WHERE 条件
SELECT FName FROM T_Employee WHERE FSalary < 5000
数据汇总(聚合函数)MAX(), MIN(), AVG(), SUM(), COUNT()
MAX() 计算字段最大值
MIN() 计算字段最小值
AVG() 计算字段平均值
SUM() 计算字段合计值
COUNT() 统计数据条数
SELECT MAX(FSalary) AS MAX_SALARY FROM T_Employee WHERE FAge > 25
SELECT AVG(FAge) FROM T_Employee WHERE FSalary > 3800
SELECT SUM(FSalary) FROM T_Employee
SELECT MAX(FSalary), MIN(FSalary) FROM T_Employee
SELECT COUNT(*), COUNT(FNumber) FROM T_Employee
**! COUNT(*)和COUNT(字段名)是又区别的 COUNT(字段名)会忽略值为NULL的记录
排序 (ORDER BY子句) ASC 升序 DESC 降序
SELECT * FROM T_Employee ORDER BY FAge ASC
SELECT * FROM T_Employee ORDER BY FAge DESC
ORDER BY 语句允许指定多个排序列,各个列之间用逗号隔开,当第一个规则无法区分两条记录时则按照第二个排序规则进行排序,依次递推。
ORDER BY 与 WHERE 一起使用, ORDER BY 子句要位于 WHERE 子句后
SELECT * FROM T_Employee
WHERE FAge > 23
ORDER BY FAge DESC, FSalary DESC
2 高级数据过滤
通配符过滤
单字符匹配: 半角下划线'_',匹配单个出现的字符
SELECT * FROM T_Employee WHERE FName LIKE '_erry'
#匹配任意字符开头,剩余部分为'erry'
-
多字符匹配:半角百分号'%',匹配任意多个字符
'k%',以k开头,任意长度字符串
'k%t',以k开头t结尾,任意长度字符串
'%n%',含有n的任意字符串
空值检测
不能用 = NULL 或 != NULL,用 IS NULL 或 IS NOT NULL
SELECT * FROM T_Employee WHERE FName IS NULL( IS NOT NULL )
范围值检测 (BETWEEN AND)
字段名 BETWEEN 左范围值 AND 右范围值
SELECT * FROM T_Employee WHERE FAge BETWEEN 23 AND 27
3 数据分组
GROUP BY
GROUP BY 常与聚合函数一起使用
没有出现在GROUP BY子句中的列(聚合函数除外)是不能放到SELECT语句后的列名列表中的
SELECT FAge, FSalary FROM T_Employee GROUP BY FAge 错
SELCET FAge, AVG(FSalary) FROM T_Employee GROUP BY FAge 对
GROUP BY 子句中可以指定多个列,用逗号隔开,GROUP BY 子句会逐层分组,形成组中组
SELECT FSubCompany, FDepartment FROM T_Employee
GROUP BY FSubCompany, FDepartment
包含ORDER BY子句的GROUP BY,按照指定字符进行排序
SELECT FSubCompany,FAge,COUNT(*) AS CountOfThisSubCompany FROM T_Employee
GROUP BY FSubCompany,FAge
ORDER BY FSubCompany
#指定按照FSubCompany排序
HVAING 子句 对部分分组进行过滤
聚合函数不能在WHERE子句中使用
SELECT FAge, COUNT(*) AS CountOfThisAge FROM T_Employee
GROUP BY FAge WHERE COUNT(*) > 1 错
所以需要用HAVING子句代替
SELECT FAge, COUNT(*) AS CountOfThisAge FROM T_Employee
GROUP BY FAge HAVING COUNT(*) > 1
**! HAVING子句能够使用的语法和WHERE子句几乎一样,NUT使用WHERE子句是GROUP BY 子句要在WHERE 子句之后,为使用HAVING子句时GROUP BY子句要位于HAVING子句之前