功能:类似于java的方法,将一组逻辑语句封装在方法体中,对外暴露方法名
好处:隐藏了实现细节,提高代码的重用性
调用:select 函数名(实参列表) 【from 表】;
一:单行函数:如:concat length ifnull等
二:分组函数
功能:做统计使用,又称为统计函数,聚合函数,组函数。
length 获取字符数值的字节个数
SELECT LENGTH('hello');
SELECT LENGTH('徐亚远');
SELECT CONCAT(last_name,'_',first_name) AS 姓名 FROM employees;
SELECT UPPER('ab');
SELECT LOWER('AB');
案例,将姓大写,名小写,然后拼接
SELECT CONCAT(UPPER(last_name),'_',LOWER(first_name)) AS 姓名 from employees;
**注意 :**索引从1开始
截取从指定索引处后面所有的字符
SELECT SUBSTR('杨过和小龙女',3) AS out_put;
截取从指定索引处指定字符长度的字符
SELECT SUBSTR('杨过和小龙女',1,3) AS out_put;
案例:姓名中首字符大写,其他字符小写然后用_拼接,显示出来
SELECT CONCAT(UPPER(SUBSTR(last_name,1,1)),'_',LOWER(SUBSTR(last_name,2)))
AS out_put
FROM employees;
SELECT INSTR('杨过和小龙女的爱情故事','小龙女') AS out_put;
SELECT LENGTH(TRIM(' 徐亚远 ')) AS out_put;
SELECT TRIM('a' FROM 'aaaaaa徐aaaaaaaaaaa亚远aaaaaaaaaaaaaaa') AS out_put;
SELECT LPAD('徐亚远',10,'*') AS out_put;
SELECT RPAD('徐亚远',12,'_') as out_put;
SELECT REPLACE('杨过和小龙女的爱情故事','小龙女','大雕') AS out_put;
SELECT ROUND(1.2);
SELECT ROUND(-1.2);
SELECT ROUND(1.234,2);
SELECT CEIL(-1.02);
SELECT FLOOR(-9.99);
SELECT TRUNCATE(1.22223,1.2);
/*
MOD(a,b): a-a/b*b
MOD(-10,-3): -10-(-10)/(-3)*(-3)=-1
*/
SELECT MOD(-10,-3);
SELECT 10%3;
SELECT NOW();
SELECT CURDATE();
SELECT CURTIME();
SELECT YEAR(NOW()) AS 年;
SELECT YEAR('2020-3-26') AS 年;
SELECT YEAR(hiredate) AS 年 FROM employees;
SELECT MONTH(NOW()) AS 月;
SELECT MONTHNAME(NOW()) AS 月;
SELECT STR_TO_DATE('2020-3-26','%Y-%c-%d') AS out_put;
案例:查询入职日期为1992-4-3的员工信息
select hiredate from employees where hiredate='1992-4-3';
SELECT hiredate FROM employees WHERE hiredate=STR_TO_DATE('4-3-1992','%c-%d-%Y');
SELECT DATE_FORMAT(NOW(),'%Y年%m月%d日') AS out_put;
案例:查询有奖金的员工名和入职日期(xx月/xx日 xx年)
SELECT last_name, DATE_FORMAT(hiredate,'%m月/%d日 %Y年') AS 入职日期
FROM employees
WHERE commission_pct is not null;
select DATEDIFF(NOW(),'1997-04-14') as 相差天数;
SELECT VERSION();
SELECT DATABASE();
SELECT USER();
SELECT IF(10>4,'大','小');
SELECT last_name,commission_pct,IF(commission_pct is NULL,'没有奖金','有奖金') AS 备注 FROM employees;
mysql中
case 要判断的字段或表达式
when 常量一:then 要显示的值1或语句1;
when 常量二: then 要显示的值2或语句2;
......
else 要显示的值n或语句n;
end
案例:查询员工的工资,要求
部门号=30,显示的工资为1.1倍
部门号=40,显示的工资为1.2倍
部门号=50,显示的工资为1.3倍
其他部门,显示的工资为原工资
select salary AS 原工资,department_id,
CASE department_id
WHEN department_id=30
THEN salary*1.1
WHEN department_id=40
THEN salary*1.2
WHEN department_id=50
THEN salary*1.3
ELSE salary
END AS 新工资
from employees;
mysql 中:
case
when 条件一 then 要显示的值1或语句1
when 条件二 then 要显示的值2或语句2
.......
else 要显示的值n或语句n
end
案例:查询员工的工资的情况
如果工资>20000,显示A级别
如果工资>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;
length
concat
substr
instx
trim
upper
lower
lpad
rpad
replace
round
ceil
floox
truncate
mod
now
curdate
curtime
year
month
monthname
day
hour
minute
second
str_to date
date format
version
database
user
if
case