zoukankan      html  css  js  c++  java
  • mysql数据库 学习(四)SQL函数

    SQL 函数

    Mysql 拥有很多可用于计数和计算的内建函数。

    • 内建 SQL 函数的语法是:SELECT function(列) FROM 表

    函数的基本类型是:

    • Aggregate 函数
    • Scalar 函数

    合计函数

    Aggregate 函数的操作面向一系列的值,并返回一个单一的值。如:

     COUNT()函数:用来统计记录的条数;
    
     SUM()函数:是求和函数; 
    
     AVG()函数:是求平均值的函数 ;
    
     MAX()函数是求最大值的函数 
    
     MIN()函数是求最小值的函数 
    

    注释:

    group by 语句经常和合计函数配合使用来进行求和、计数、求平均值、求最大值和求最小值。

    我使用的是mysql 8.0.25 使用group by 这儿出现了一个问题(bug)

    https://www.feiniaomy.com/post/475.html

    -- 分组
    select * from stu s group by s.s_sex;
    -- 聚合函数
    select avg(s_score) as '平均分',max(s_score) as '最高分',min(s_score) as '最低分',s_sex as '性别'  from stu group by s_sex;
    
    
    
    

    标量函数

    -- 取绝对 
    -- dual 代码数据库内存
    select abs(-123) from dual;
    -- 日期
    select date("2021-9-7");
    -- 时间
    select now() from dual;
    -- 返回日期
    select adddate("2021-9-7",3);
    -- 返回时间
    select addtime("2021-9-7","2021-9-8");
    
    -- 添加日期字段 
    alter table stu add column birthday date;
    -- 生日在30天之内的 sql
    select * from stu where date(birthday)
    select * from stu where date(birthday) >= ("2021-9-7") and ("2021-8-7")
    select * from stu where birthday > date_sub(birthday,interval 30 day);
    select * from stu where birthday > date_add("2021-8-7",interval 30 day);
    select * from stu where datediff(now(),birthday)<30;
    select * from stu where birthday > date_sub(now(),interval 30 day);
    -- 日期相减
    select * from stu where datediff(now(),birthday) < 30;
    -- 当前日期的前三十天和后三十天 (DATE_SUB函数本身是减法,用负数就是加)
    -- 生日在30天之内的 sql 
    SELECT * from stu
    where birthday between DATE_SUB(NOW(),INTERVAL 30 day) and DATE_SUB(NOW(),INTERVAL -30 day)
    
    -- 当前时间
    select now();
    -- 前三十天
    select DATE_SUB(now(), INTERVAL 30 DAY);
    -- 后三十天(函数本身是减法,用负数就是加)
    select DATE_SUB(now(), INTERVAL -30 DAY);
    -- 减去一个月
    select DATE_SUB(now(), INTERVAL 1 month);
    -- 减一年
    select DATE_SUB(now(), INTERVAL 1 year);
    
    -- 统计
    select count(*) from stu;
    --分组
    select * from stu group by s_sex having avg(s_score) >= 80;
    --分组
    select * from stu  where s_score > 80  group by s_sex having avg(s_score) >= 80;
    

    date 函数

    date 数据类型

    MySQL 使用下列数据类型在数据库中存储日期或日期/时间值:
    
     - DATE - 格式 YYYY-MM-DD
     - DATETIME - 格式: YYYY-MM-DD HH:MM:SS
     - TIMESTAMP - 格式: YYYY-MM-DD HH:MM:SS
     - YEAR - 格式 YYYY 或 YY
    
  • 相关阅读:
    输入挂
    最长递增子序列nlogn的做法
    lca 倍增模版
    讨厌字符串
    js的事件处理与闭包:
    http
    html的语义化
    js性能优化
    js的缓存
    字面量声明和函数式声明
  • 原文地址:https://www.cnblogs.com/d534/p/15238525.html
Copyright © 2011-2022 走看看