# 字段用','隔开,至少有一个字段,最终结果集按照这个这个顺序显示
select 字段1,字段2... from 表名;
# *代表所有字段
select * from 表名;
distinct(去重)
# 去重后的结果,distinct必须紧接着select后面
select distinct 字段 from 表名;
# 统计不重复的个数
select count(distinct 字段) from 表名;
where子句
类型 运算符
算术 + - * / %
比较 > < >= <= != =
逻辑 or || and && not !
提升优先级 ( )
案例:
# 搜索id<20的所以数据
select * from students where id<20;
# 搜索id编号为偶数的数据
select * from students where id%2=0;
where条件关键字
in:查询一个集合的数据
# 搜索id在(1,3,7)之中的数据
select * from students where id=1 || id=3 || id=7;
select * from students where id in(1,3,7);
# 一次删除多条记录
delete from students where id=3 || id=15 || id=23;
delete from students where id in(3,15,23);
between...and... :查询一个区间的数据
# 搜索id在20-40之间的数据
select * from students where id>20 && id<40;
select * from students where id between 20 and 40;
# 删除id在20-40之间的数据
delete from students where id between 20 and 40;
not:排除
# 搜索id除了20-40之间的数据
select * from students where id not between 30 and 40;
like 子句
用于模糊查询 %:任意字符长度 _ :一个字符长度
# 搜索name名字以5结尾的数据
select * from students where name like '张%';
# 搜索name名字包含字母s的数据
select * from students where name like '%二%';
# 搜索id以5结尾的两位数 数据
select * from students where id like '_5';
limit 子句
控制查询记录条数,数据表中的记录,索引从0开始
select * from students limit 2 # 返回两条记录
select * from students limit 3,4 # 从索引为3的记录开始,返回4条记录
# php中的分页功能,偏移值的计算:(当前页-1) * 每页记录数
select name from student limit 4 offset 3
# 还可以使用offset(偏移):从索引为3的记录开始,返回4条
group by(结果分组)
根据给定数据列的每个成员对查询结果进行分组统计,最终得到一个分组汇总表
利用group by分组信息进行统计,常见的是配合max等聚合函数筛选数据后分析。
select指定的字段要么作为分组的依据(Group By语句的后面),要么就要被包含在聚合函数中。
# 简单分组
select sex from students group by sex;
+-----+
| sex |
+-----+
| m |
| w |
+-----+
# 聚合函数分组
select count(*),city from students group by city;
+----------+----------+
| count(*) | livecity |
+----------+----------+
| 7 | 1 |
| 8 | 2 |
| 1 | 3 |
| 3 | 4 |
| 2 | 5 |
+----------+----------+
order der(结果排序)
按照给定的字段进行排序,asc:升序(默认) desc:降序
如果同时选择多个字段,先按第一个字段排序,如果第一个字段值相等,再尝试第二个字段,以此类推
# 默认升序
select * from students order by birthday;
# 降序
select * from students order by birthday desc;
查询语句的书写顺序
select →字段→ from→表名→where→group by→order by→limit
别名