MySQL(关系型数据库)-函数[聚合函数、数学函数、字符串函数]

聚合函数

/*
概述:
聚合函数主要由:count,sum,min,max,avg,
group_concat()函数首先根据group by指定的列进行分组,并且用分隔符分隔,将同一个分组中的值连接起来,返回一个字符串结果。
格式:
group_concat([distinct] 字段名 [order by 排序字段 asc/desc] [separator '分隔符'])
说明:
  (1)使用distinct可以排除重复值;
  (2)如果需要对结果中的值进行排序,可以使用order by子句;
  (3)separator是一个字符串值,默认为逗号。
*/

create database MyTestdb;
use MyTestdb;

create table emp(
    emp_id int primary key auto_increment comment '编号',
    emp_name char(20) not null default '' comment '姓名',
    salary decimal(10,2) not null default 0 comment '工资',
    department char(20) not null default '' comment '部门'
);
 
insert into emp(emp_name,salary,department) 
values('张晶晶',5000,'财务部'),('王飞飞',5800,'财务部'),('赵刚',6200,'财务部'),('刘小贝',5700,'人事部'),
('王大鹏',6700,'人事部'),('张小斐',5200,'人事部'),('刘云云',7500,'销售部'),('刘云鹏',7200,'销售部'),
('刘云鹏',7800,'销售部');


-- 将所有员工的名字合并成一行
select group_concat(emp_name) from emp;

-- 指定分隔符合并
select group_concat(emp_name separator ';') from emp;

-- 指定排序方式和分隔符
select department,group_concat(emp_name separator ';') from emp group by department;
select department,group_concat(emp_name order by salary desc separator ';') from emp group by department;

数学函数

-- 求绝对值;返回 x 的绝对值
select abs(-10);-- 返回10
select abs(表达式或字段) from;

-- 向上取整;返回大于或等于 x 的最小整数
select ceil(1.1);-- 返回2
select ceil(1.0);-- 返回1

-- 向下取整;返回小于或等于 x 的最大整数  
select floor(1.1);-- 返回1
select floor(1.9);-- 返回1

-- 返回列表中的最大值
select greatest(1,2,3);-- 返回3

-- 返回列表中的最小值
select least(1,2,3);-- 返回1

-- 取模;返回 x 除以 y 以后的余数
select mod(5,2);-- 返回1

-- 返回 x 的 y 次方
select pow(2,3);-- 返回8

-- 取随机数;返回 0 到 1 的随机数 
select rand();
select floor(rand()*100);

-- 将小数 四舍五入取 整
select round(3.5415);-- 返回4

-- 将小数 四舍五入取 指定位数小数
select round(3.5415,3);-- 返回3.542

-- 将小数 直接截取到 指定位数
select truncate(3.1415,3);-- 返回3.141

字符串函数

-- 获取字符串字符个数
select char_length('hello');-- 返回5
select char_length('你好吗');-- 返回3

-- length取长度,返回单位是字节
select length('hello');-- 5
select length('你好吗');-- 9

-- 字符串合并
select concat('hello','world');-- helloworld

-- 指定分隔符进行字符串合并
select concat_ws('-','hello','world');-- hello-world

-- 返回字符串在列表中第一次出现的位置
select field('aaa','aaa','bbb','ccc');-- 1
select field('bbb','aaa','bbb','ccc');-- 2

-- 去除字符串左边空格
select ltrim('   aaa');

-- 去除字符串右边空格
select rtrim('aaa     ');

-- 去除字符串两边空格
select trim('        aaa     ');

-- 字符串截取
select mid("helloworld",2,3);-- 从第二个字符开始截取,截取长度为3

-- 获取字符串A在字符串中出现的位置
select position('abc' in 'habcelloabcworld');-- 2

-- 字符串替换
select replace('aaahelloaaaworld','aaa','bbb');-- bbbhellobbbworld

-- 字符串反转
select reverse('hello');-- olleh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值