一、单表查询的语法
SELECT 字段1,字段2... FROM 表名
WHERE 条件
GROUP BY field
HAVING 筛选
ORDER BY field
LIMIT 限制条数
二、关键字的执行优先级(重点)
重点中的重点:关键字的执行优先级fromwhere
group by
having
select
distinct
order by
limit
1.找到表:from
2.拿着where指定的约束条件,去文件/表中取出一条条记录
3.将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组
4.将分组的结果进行having过滤
5.执行select
6.去重
7.将结果按条件排序:order by
8.限制结果的显示条数
查询
给表起别名,用在SQL语句同时查询多张表,又不想写太多表名的情况下
select s.name, s.gender from students2 as s;
去重
select distinct gender from students2; # 只显示有多少种性别,而不是多少个性别
条件查询
比较运算
> = <= !=
select * from students2 where age = 18; #一个等号=就行
and
select name from students2 where age > 18 and gender="女";
条件:不在 18岁以上的女性 这个范围内的信息
select * from students2 where not (age > 18 and gender="女");
易错
select * from students2 where not age > 18 and gender="女";
模糊查询
like
% 替换一个或者多个
_ 替换一个
查询姓名中以“小”开始的名字
select name from students2 where name like "小%";
查询姓名中有“小”所有的名字
select name from students2 where name like "%小%";
查询有两个字的名字
select * from students2 where name like "__";
查询至少有两个字的名字
select * from students2 where name like "__%";
rlike 正则
查询以小开始的姓名
select name from students2 where name rlike "^小.*";
范围查询
in(1, 3, 8)表示在一个非连续的范围内
查询年龄为12, 18, 21的信息
select * from students2 where age in (12, 18, 21);
查询年龄不为12, 18, 21的信息
select * from students2 where age not in (12, 18, 21);
between ... and ... 表示在一个连续的范围内
查询年龄在12到18之间的信息
select * from students2 where age between 12 and 18;
查询年龄不在12到18之间的信息
select * from students2 where age not between 12 and 18;
不能加括号:
select * from students2 where age not (between 12 and 18);
空判断
判空 is null