MySQL - SELECT - 语句
as语句
mysql> select TT.studentno 学号 ,TT.courseno 课程号 , -> TT.final*0.8+TT.daily*0.2 总评 -> from (select * from score where final>90) as TT -> where TT.final*0.8+TT.daily*0.2>85;
基本限制语句
distinct
DISTINCT 关键词用于返回唯一不同的值。
也就是:自动去重
使用
select distinct studentno,courseno -> from score -> where daily >90
and
当有两个限制条件时候,使用and连接
使用
-> where courseno='c08126' and daily between 85 and 100;
范围限制
选择一个范围内的数据
使用
-> where daily between 85 and 100;
排序、分组和限定记录
order by
对结果集进行排序。
默认是升序排列,(也可用关键字asc表示升序)
如果需要降序,使用desc关键字。
select from where order by column_name,column_name desc;
group by
通过列或表达式的值
将一组行分组为一个小分组的汇总行记录。
GROUP BY子句为每个分组返回一行。
换句话说,它减少了结果集合中的行数。
比如说:对于某大学的全部学生表,如果按照男女分组,就只有两组,返回两行。
使用
select from where group by column_name
with rollup
在group分组字段的基础上再进行统计数据。
比如说:统计平均分
加入该字段后会再统计分组后的平均值
group_concat
返回带有来自一个组的连接的非 NULL 值的字符串结果。
使用
GROUP_CONCAT( distinct order by separator )
distinct:去除重复值
order by:根据字段或表达式进行排序
separator str_val:分隔符(默认为英文逗号)
使用场景
https://shockerli.net/post/mysql-function-group_concat/
- 结合 GROUP BY 查询
select column_name,group_concat(column_name) from group by column_name;
having count
没有分组的情况下having和Where 类似。
有分组的时候 Where对分组前内容过滤,having是分组后的内容进行筛选。
select xxx from xxxx group by xxxx having count(*) > 2
having作用是将分组后的元素大于2的显示。
使用的限制语句和where一样,where能用having就能用
使用
select from where group by having
limit
作用:显示从第x行开始,计数y行的信息。
使用
select from where order by limit starting_point , end_point;
聚合函数
聚合函数aggregation function。
默认情况下 聚合函数会对当前所在表当做一个组进行统计。
常用于GROUP BY从句的SELECT查询中
特点
- 每个组函数接收一个参数(字段名或者表达式) 统计结果中默认忽略字段为NULL的记录
- 要想列值为NULL的行也参与组函数的计算,必须使用IFNULL函数对NULL值做转换。
- 不允许出现嵌套 比如sum(max(xx))
left
作用切割字符的前x个字符
left(student.studentno,2)='19'
常用聚合函数
ROUND(column_name,decimals)
column_name:要舍入的字段。必须要填。
decimals 规定要返回的小数位数。可选,缺省值是四舍五入到整数
AVG(col)返回指定列的平均值
COUNT(col)返回指定列中非NULL值的个数
MIN(col)返回指定列的最小值
MAX(col)返回指定列的最大值
SUM(col)返回指定列的所有值之和
GROUP_CONCAT(col) 返回由属于一组的列值连接组合而成的结果
子查询
例:
select studentno,sname,phone,Email from student where studentno in ( select studentno from score where final>90);
查找score表中所有比c05103课程期末成绩都高的学号、姓名、电话和期末成绩。
mysql> select student.studentno,sname,phone,final -> from score inner join student -> on score.studentno=student.studentno -> where final>all -> (select final from score where courseno='c05126');
正则表达式
https://blog.csdn.net/lonelymanontheway/article/details/118197636
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/16209535.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步