一 单行函数
1 字符函数
#length 获取参数值的字节个数
select length('jone');
select length('张三丰hhh');#15 字节个数不等于字符个数
show variables like '%char%';#字符集
#concat 拼接字符串
select concat(last_name,'_',first_name) 姓名 employees;
#upper lower变大小写
select upper(‘jkoe’) ;
select lower(‘JKIO’);
案例 将姓变大写 名变小写 然后拼接
SELECT CONCAT(UPPER(last_name),LOWER(first_name)) 姓名 FROM employees;
# substr substring
注意: 索引从1 开始
#截取从指定索引处后面所有字符
SELECT CONCAT(UPPER(last_name),LOWER(first_name)) 姓名 FROM employees;
#截取从指定索引处指定字符长度的字符 (李莫愁)
SELECT SUBSTR('李莫愁爱上了路站元',1,3) out_put;
#案例 姓名中首字符大写 其他字符小写然后用_拼接 显示出来
SELECT CONCAT(UPPER(SUBSTR(last_name,1,1)),'_',LOWER(SUBSTR(last_name,2))) out_put
FROM employees;
# instr 返回字串第一次出现的索引 如果找不到返回0
SELECT INSTR('杨不悔爱上了殷六霞','殷六霞') out_put
FROM employees;
# trim (去除前后空格 计算字节数)
SELECT LENGTH(TRIM(' 张翠山 ')) out_put; # 9
SELECT LENGTH(TRIM(' zzz ')) out_put; # 3
SELECT LENGTH(TRIM(' z zz ')) out_put; # 5
SELECT TRIM('a' FROM 'aaaaa张aaa翠山aaaa') out_put; # 张aaa翠山
#7 lpad 用指定字符实现左填充指定长度
SELECT LPAD('殷素素',10,'*') out_put; #*******殷素素
#8 rpad 用指定字符实现右填充指定长度
SELECT RPAD('殷素素',12,'ab') out_put; #殷素素ababababa
#9 replace 替换
SELECT REPLACE('周芷若周芷若爱上了张无忌','周芷若','赵敏') out_put; #赵敏赵敏爱上了张无忌
2 数学函数
# round 四舍五入
SELECT ROUND(-1.78);# -2
SELECT ROUND(1.7866,2);# 1.79 四舍五入保留两位小数
#ceil 向上取整,返回>=该参数的最小整数
SELECT CEIL(-1.02); #-1
#floor 向下取整 返回15000,显示B级别
如果工资>10000,显示C级别
否则,显示D级别
SELECT salary,
CASE
WHEN salary>20000 THEN 'A'
WHEN salary>15000 THEN 'B'
WHEN salary>10000 THEN 'C'
ELSE 'D'
END AS 工资级别
FROM employees;
例题
#1. 显示系统时间(注:日期+时间)
SELECT NOW();
#2. 查询员工号,姓名,工资,以及工资提高百分之20%后的结果(new salary)
SELECT employee_id,last_name,salary,salary*1.2 "new salary"
FROM employees;
#3. 将员工的姓名按首字母排序,并写出姓名的长度(length)
SELECT LENGTH(last_name) 长度,SUBSTR(last_name,1,1) 首字符,last_name
FROM employees
ORDER BY 首字符;
#4. 做一个查询,产生下面的结果
earns monthly but wants
Dream Salary
King earns 24000 monthly but wants 72000
SELECT CONCAT(last_name,' earns ',salary,' monthly but wants ',salary*3) AS "Dream Salary"
FROM employees
WHERE salary=24000;
#5. 使用case-when,按照下面的条件:
job grade
AD_PRES A
ST_MAN B
IT_PROG C
SA_REP D
ST_CLERK E
产生下面的结果
Last_name Job_id Grade
king AD_PRES A
SELECT last_name,job_id AS job,
CASE job_id
WHEN 'AD_PRES' THEN 'A'
WHEN 'ST_MAN' THEN 'B'
WHEN 'IT_PROG' THEN 'C'
WHEN 'SA_PRE' THEN 'D'
WHEN 'ST_CLERK' THEN 'E'
END AS Grade
FROM employees
WHERE job_id = 'AD_PRES';