MySQL--单表查询
1. 简单数据记录查询(可用*表示查询全部字段)
SELECT field1, field2, ... FROM table_name;
1.1 查询结果去重(DISTINCT)
SELECT DISTINCT field1, field2, ... FROM table_name;
2. 条件数据记录查询(WHERE)
SELECT * FROM table_name WHERE 条件;
2.1 范围查询
SELECT * FROM table_name WHERE field [NOT ]BETWEEN value1 AND value2;
2.2 [非]空值查询
SELECT * FROM table_name WHERE field IS [NOT ]NULL;
2.3 集合查询
NOT IN 查询的集合中存在NULL则不会有任何查询结果
IN 查询的集合中存在NULL和无NULL的查询结果一致
SELECT * FROM table_name WHERE field [NOT ]IN (value1, value2, ...);
2.4 模糊查询
"_" 通配符, 匹配单个字符
"%" 通配符, 匹配任意长度的字符
SELECT * FROM table_name WHERE field [NOT ]LIKE value;
SELECT * FROM table_name WHERE field REGEXP 正则表达式;
3. 排序数据记录查询
ORDER BY默认为ASC升序排序
SELECT * FROM table_name ORDER BY field1 [ASC|DESC][, field2 [ASC|DESC], ...]
4. 限制数据记录查询数量
起始偏移量(跳过的行数)默认为0
SELECT * FROM table_name LIMIT [起始偏移量, ]显示的行数
5. 统计函数及分组查询
5.1 统计函数
SELECT function(field) FROM table_name
COUNT(*) 统计数据记录条数, 不管是否是NULL
COUNT(field) 此统计会忽略该字段的NULL值
COUNT() | 统计 | MAX() | 最大值 | |
AVG() | 平均值 | MIN() | 最小值 | |
SUM() | 求和 |
5.2 分组查询
可以SELECT*但分组字段每个值只会显示一条记录
SELECT function(field) FROM table_name GROUP BY field1[, field2, ...]
5.3 分组查询--HAVING子句限定分组查询
SELECT function(field) FROM table_name WHERE CONDITION GROUP BY field1[, field2, ...] HAVING CONTITION