5. Select 查询数据语句
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
(1). SELECT 显示字段
显示表的所有字段:SELECT * FROM person;
显示表的固定字段:SELECT name, age, id FROM person;
显示表的固定字段,固定字段以别名输出:SELECT name stu_n, age stu_a, id stu_i FROM person;
以表达式显示表(会把age列全部加1,空值仍然还是空值):SELECT (age+1) stu_a, id FROM person;
(2). FROM 指定表
指定特定表:SELECT * FROM person;
指定表的特定字段方式显示:SELECT person.name, person.age, id FROM person;
指定表起别名(有时候表名太长):SELECT p.name FROM person p;
(3). WHERE 条件
A. 比较运算符(6个)
通过比较运算符查询:SELECT * FROM person WHERE age > 18;
通过比较运算符查询:SELECT * FROM person WHERE age >= 18;
通过比较运算符查询:SELECT * FROM person WHERE age < 18;
通过比较运算符查询:SELECT * FROM person WHERE age <= 18;
通过比较运算符查询:SELECT * FROM person WHERE age = 18;
通过比较运算符查询:SELECT * FROM person WHERE age != 18;
B. 逻辑运算符(3个)
通过 AND 逻辑与、表示并且的意思:SELECT * FROM person WHERE age > 18 AND age < 50 AND sex=‘男’;
通过 OR 逻辑或、表示或者的意思:SELECT * FROM person WHERE age = 18 OR age = 50;
通过 NOT 逻辑非、表示取反的意思(一般与其他运算符连用):SELECT * FROM person WHERE age IS NOT NULL; 或者 SELECT * FROM person WHERE name NOT LIKE ‘AAA’;
C. 其他运算符(4个)
通过 BETWEEN AND 查询数字区间、包含边界值:SELECT * FROM person WHERE age BETWEEN 18 AND 50;
通过 IN 查询数据区间:SELECT * FROM person WHERE name IN(‘王五’, ‘李四’, ‘张三’)
通过 LIKE 模糊查询、搜索功能、必须是字符类型varchar:
匹配符_: 匹配的是一个任意字符(1个、几乎不用):SELECT * FROM person WHERE name LIKE ‘王_’; 或者 SELECT * FROM person WHERE name LIKE ‘AAA’;
匹配符%: 匹配的是零个或者多个任意字符(任意个、用的多):SELECT * FROM person WHERE name LIKE ‘王%’; 或者 SELECT * FROM person WHERE name LIKE ‘%王%’;
通过 NULL 空、表示什么也没有、表示未知的意思(与 is 连用):SELECT * FROM person WHERE age IS NULL;
(4). GROUP BY 分组显示:相同的就是一组、显示组的信息。
通常必须和聚合统计类函数(MAX、SUM、MIN、AVG、COUNT等)一起使用:
通过 分组 显示:SELECT sex, MAX(age), MIN(age) FROM person GROUP BY sex;
(5). HAVING 分组条件
注意:having 必须和 group by 一起使用。
where条件对是表中每一条记录进行过滤。分组之前运行
having条件对分组之后的每一条记录进行过滤。分组之后运行
通过 having 条件(having是对group by执行完后的数据再次筛选):SELECT sex, count() FROM person WHERE name != ‘abc’ GROUP BY sex HAVING count() > 2;
(6). ORDER BY 排序
通过 ORDER BY 排序(比如按照年龄排序、默认升序):SELECT * FROM person ORDER BY age;
通过 ORDER BY 的 ASC 升序排序:SELECT * FROM person ORDER BY age ASC;
通过 ORDER BY 的 DESC 降序排序:SELECT * FROM person ORDER BY age DESC;