这是我参与「第五届青训营」伴学笔记创作活动的第2天
Mysql学习笔记
SELECT语句
语法
- 基础语法:select 字段列表 from 数据源;
- 完整语法:select 去重选项 字段列表 [as 字段别名] from 数据源 [where子句] [group by 子句] [having子句] [order by 子句] [limit子句];
去重选项
去重选项是对结果中完全相同的记录进行去重
-
参数:
- all:不去重
- distinct:去重
-
语法:select 去重选项 字段列表 from 表名;
例:
题目:现在运营需要查看用户来自于哪些学校,请从用户信息表中取出学校的去重数据。
示例:user_profile
根据示例,你的查询应返回以下结果:
输入:
drop table if exists user_profile; CREATE TABLE `user_profile` ( `id` int NOT NULL, `device_id` int NOT NULL, `gender` varchar(14) NOT NULL, `age` int , `university` varchar(32) NOT NULL, `province` varchar(32) NOT NULL); INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学','BeiJing'); INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学','Shanghai'); INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学','BeiJing'); INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大学','ZheJiang'); INSERT INTO user_profile VALUES(5,5432,'male',25,'山东大学','Shandong');输出:
北京大学 复旦大学 浙江大学 山东大学
Answer:
SELECT DISTINCT university FROM user_profile;
字段别名
字段别名是给查询结果中的字段另起一个名字,只会在单次查询时生效
- 语法:select 字段 as 字段别名 from 表名;
例:
before:
use:
select
name as '姓名',
gender as '性别'
from user_profile
after:
where子句
where子句用于筛选符合条件的结果
-
语法:
-
基于值:
- =: where 字段 = 值; 用于精准匹配查找结果 (<是小于对应值,<=是小于等于对应值,>是大于对应值,>=是大于等于对应值,!=是不等于) [例:where name = 'yuleng'; ]
- like: where 字段 like 值; 用于模糊匹配查找结果 [例:where name = 'y%'; ]
-
基于值得范围:
- in: where 字段 in 范围; 用于查找对应字段的值在指定范围的记录 [例:where age in (16,17); ]
- not in: where 字段 not in 范围; 用于查找对应字段的值不在指定范围的记录 [例:where age not in (16,17); ]
- between x and y: where 字段 between x and y; 用于查找对应字段在某个范围区间的记录 [例:where age between 15 and 16; ]
-
条件复合:
- or: where 条件1 or 条件2...; 查找出符合条件1或条件2的记录 [例:where age > 10 or age < 2; ]【可用 || 替换】
- and: where 条件1 and 条件2...; 查找出既符合条件1也条件2的记录 [例:where age > 10 and age > 8; ] 【可用 && 替换】
- not: where not 条件1; 找出不符合条件的所有记录 [例:where not age <10; ] 【可用 !替换】
-
having子句
having的判断在内存中的条件,例如“分组”,“字段别名”等,除此之外,与where类似!
- 语法:select 字段列表 from 表名 having 条件;
group by子句
group by 可以将查询结果依据字段来将结果分组
- 语法:select 字段列表 from 表名 group by 字段;(字段可以有多个 即多次分组)
例:
计算每个学校每种性别的用户数、30天内平均活跃天数和平均发帖数量。
SELECT gender,university, COUNT(device_id) as user_num, ROUND(AVG(active_days_within_30),1) as avg_active_day, ROUND(AVG(question_cnt),1) as avg_question_cnt FROM user_profile GROUP BY gender,university分组后:
-
一般group by将会配合一些统计函数使用:
- count(x):统计每组的记录数,x是*时代表记录数,为字段名时代表统计字段数据数(除去NULL)
- max(x):统计最大值,x是字段名
- min(x):统计最小值,x是字段名
- avg(x):统计平均值,x是字段名
- sum(x):统计总和,x是字段名
-
group by 字段 后面还可以跟上asc或desc,代表分组后是否根据字段排序。
order by子句
order by子句使查询结果按照某个字段进行排序
- 语法:select 字段列表 from 表名 order by 字段 [asc(升序)/desc(降序)];
- 只需要在每个字段后面加asc或desc就可以实现对单独字段的排序
UNION 操作符
MySQL UNION 操作符用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。
-
语法:
SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] UNION [ALL | DISTINCT] SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions]; -
参数:
- DISTINCT: 可选,删除结果集中重复的数据。默认情况下 UNION 操作符已经删除了重复数据,所以 DISTINCT 修饰符对结果没啥影响。
- ALL: 可选,返回所有结果集,包含重复数据。