1 函数的理解
1.1 什么是函数
函数在计算机语言的使用中贯穿始终,函数的作用是什么呢?它可以把我们经常使用的代码封装起来,需要的时候直接调用即可。这样既 提高了代码效率 ,又 提高了可维护性 。在SQL 中我们也可以使用函数对检索出来的数据进行函数操作。使用这些函数,可以极大地 提高用户对数据库的管理效率 。
从函数定义的角度出发,我们可以将函数分成 内置函数 和 自定义函数 。在 SQL 语言中,同样也包括了内置函数和自定义函数。内置函数是系统内置的通用函数,而自定义函数是我们根据自己的需要编写的,本章及下一章讲解的是 SQL 的内置函数。
1.2 不同DBMS函数的差异
在使用 SQL 语言的时候,不是直接和这门语言打交道,而是通过它使用不同的数据库软件,即DBMS。DBMS 之间的差异性很大,远大于同一个语言不同版本之间的差异。实际上,只有很少的函数是被 DBMS 同时支持的。比如,大多数 DBMS 使用(||)或者(+)来做拼接符,而在 MySQL 中的字符串拼接函数为concat()。大部分 DBMS 会有自己特定的函数,这就意味着采用 SQL 函数的代码可移植性是很差的,因此在使用函数的时候需要特别注意。
MySQL提供了丰富的内置函数,这些函数使得数据的维护与管理更加方便,能够更好地提供数据的分析与统计功能,在一定程度上提高了开发人员进行数据分析与统计的效率。
MySQL提供的内置函数从 实现的功能角度 可以分为数值函数、字符串函数、日期和时间函数、流程控制函数、加密与解密函数、获取MySQL信息函数、聚合函数等。这里将这些丰富的内置函数再分为两类: 单行函数 、 聚合函数(或分组函数) 。
两种SQL函数
单行函数
- 操作数据对象
- 接受参数返回一个结果
- 只对一行进行变换
- 每行返回一个结果
- 可以嵌套
- 参数可以是一列或一个值
2 数值函数
2.1 基本函数
#1.数值函数 #基本的操作 SELECT ABS(-123),ABS(32),SIGN(-23),SIGN(43),PI(),CEIL(32.32),CEILING(-43.23),FLOOR(32.32), FLOOR(-43.23),MOD(12,5),12 MOD 5,12 % 5 FROM DUAL; /* +-----------+---------+-----------+----------+----------+-------------+-----------------+--------------+---------------+-----------+----------+--------+ | ABS(-123) | ABS(32) | SIGN(-23) | SIGN(43) | PI() | CEIL(32.32) | CEILING(-43.23) | FLOOR(32.32) | FLOOR(-43.23) | MOD(12,5) | 12 MOD 5 | 12 % 5 | +-----------+---------+-----------+----------+----------+-------------+-----------------+--------------+---------------+-----------+----------+--------+ | 123 | 32 | -1 | 1 | 3.141593 | 33 | -43 | 32 | -44 | 2 | 2 | 2 | +-----------+---------+-----------+----------+----------+-------------+-----------------+--------------+---------------+-----------+----------+--------+ */ #取随机数(其中的参数称为种子,种子相同的两个RAND函数每次结果都一样且不变) SELECT RAND(),RAND(),RAND(10),RAND(10),RAND(-1),RAND(-1) FROM DUAL; /* +---------------------+--------------------+--------------------+--------------------+--------------------+--------------------+ | RAND() | RAND() | RAND(10) | RAND(10) | RAND(-1) | RAND(-1) | +---------------------+--------------------+--------------------+--------------------+--------------------+--------------------+ | 0.23112941927381736 | 0.8571839666526615 | 0.6570515219653505 | 0.6570515219653505 | 0.9050373219931845 | 0.9050373219931845 | +---------------------+--------------------+--------------------+--------------------+--------------------+--------------------+ */ #四舍五入:RAND(操作数,保留小数的位数) SELECT ROUND(123.556),ROUND(123.456,0),ROUND(123.456,1),ROUND(123.456,2), ROUND(123.456,-1),ROUND(153.456,-2) FROM DUAL; /* +----------------+------------------+------------------+------------------+-------------------+-------------------+ | ROUND(123.556) | ROUND(123.456,0) | ROUND(123.456,1) | ROUND(123.456,2) | ROUND(123.456,-1) | ROUND(153.456,-2) | +----------------+------------------+------------------+------------------+-------------------+-------------------+ | 124 | 123 | 123.5 | 123.46 | 120 | 200 | +----------------+------------------+------------------+------------------+-------------------+-------------------+ */ #截断操作:TRUNCATE(操作数,保留小数的位数) SELECT TRUNCATE(123.456,0),TRUNCATE(123.496,1),TRUNCATE(129.45,-1) FROM DUAL; /* +---------------------+---------------------+---------------------+ | TRUNCATE(123.456,0) | TRUNCATE(123.496,1) | TRUNCATE(129.45,-1) | +---------------------+---------------------+---------------------+ | 123 | 123.4 | 120 | +---------------------+---------------------+---------------------+ */ #单行函数可以嵌套 SELECT TRUNCATE(ROUND(123.456,2),0) FROM DUAL; /* +------------------------------+ | TRUNCATE(ROUND(123.456,2),0) | +------------------------------+ | 123 | +------------------------------+ */
2.2 角度与弧度
SELECT RADIANS(30),RADIANS(45),RADIANS(60),RADIANS(90), DEGREES(2*PI()),DEGREES(RADIANS(60)) FROM DUAL; /* +--------------------+--------------------+--------------------+--------------------+-----------------+----------------------+ | RADIANS(30) | RADIANS(45) | RADIANS(60) | RADIANS(90) | DEGREES(2*PI()) | DEGREES(RADIANS(60)) | +--------------------+--------------------+--------------------+--------------------+-----------------+----------------------+ | 0.5235987755982988 | 0.7853981633974483 | 1.0471975511965976 | 1.5707963267948966 | 360 | 59.99999999999999 | +--------------------+--------------------+--------------------+--------------------+-----------------+----------------------+ */
2.3 三角函数
举例:
ATAN2(M,N)函数返回两个参数的反正切值。 与ATAN(X)函数相比,ATAN2(M,N)需要两个参数,例如有两个点point(x1,y1)和point(x2,y2),使用ATAN(X)函数计算反正切值为ATAN((y2-y1)/(x2-x1)),使用ATAN2(M,N)计算反正切值则为ATAN2(y2-y1,x2-x1)。由使用方式可以看出,当x2-x1等于0时,ATAN(X)函数会报错,而ATAN2(M,N)函数则仍然可以计算。
#三角函数 SELECT SIN(RADIANS(30)),DEGREES(ASIN(1)),TAN(RADIANS(45)),DEGREES(ATAN(1)) FROM DUAL; /* +---------------------+------------------+--------------------+------------------+ | SIN(RADIANS(30)) | DEGREES(ASIN(1)) | TAN(RADIANS(45)) | DEGREES(ATAN(1)) | +---------------------+------------------+--------------------+------------------+ | 0.49999999999999994 | 90 | 0.9999999999999999 | 45 | +---------------------+------------------+--------------------+------------------+ */
2.4 指数函数、对数函数
#指数 SELECT POW(2,5),POWER(2,4),EXP(2) FROM DUAL; /* +----------+------------+------------------+ | POW(2,5) | POWER(2,4) | EXP(2) | +----------+------------+------------------+ | 32 | 16 | 7.38905609893065 | +----------+------------+------------------+ */ #对数 SELECT LN(EXP(2)),LOG(EXP(2)),LOG10(10),LOG2(4) FROM DUAL; /* +------------+-------------+-----------+---------+ | LN(EXP(2)) | LOG(EXP(2)) | LOG10(10) | LOG2(4) | +------------+-------------+-----------+---------+ | 2 | 2 | 1 | 2 | +------------+-------------+-----------+---------+ */
2.5 进制间的转换
#进制间的转换 SELECT BIN(10),HEX(10),OCT(10),CONV(10,10,8) FROM DUAL; /* +---------+---------+---------+---------------+ | BIN(10) | HEX(10) | OCT(10) | CONV(10,10,8) | +---------+---------+---------+---------------+ | 1010 | A | 12 | 12 | +---------+---------+---------+---------------+ */
3 字符串函数
注意:MySQL中,字符串的位置是从1开始的。
#3. 字符串函数 #ASCII:求字符串中第一个字符的ASCII码 #CHAR_LENGTH:求字符串长度CHAR_LENGTH #LENGTH:字符串所占字节数 SELECT ASCII('Abcdfsf'),CHAR_LENGTH('hello'),CHAR_LENGTH('我们'), LENGTH('hello'),LENGTH('我们') FROM DUAL; /* +------------------+----------------------+-----------------------+-----------------+------------------+ | ASCII('Abcdfsf') | CHAR_LENGTH('hello') | CHAR_LENGTH('我们') | LENGTH('hello') | LENGTH('我们') | +------------------+----------------------+-----------------------+-----------------+------------------+ | 65 | 5 | 2 | 5 | 6 | +------------------+----------------------+-----------------------+-----------------+------------------+ */ #CONCAT:字符串拼接 # xxx worked for yyy SELECT CONCAT(emp.last_name,' worked for ',mgr.last_name) "details" FROM employees emp JOIN employees mgr WHERE emp.`manager_id` = mgr.employee_id; /*部分输出 +--------------------------------+ | details | +--------------------------------+ | Kochhar worked for King | | De Haan worked for King | | Hunold worked for De Haan | */ #CONCAT_WS:用第一个参数分隔连接后面的字符串 SELECT CONCAT_WS('-','hello','world','hello','beijing') FROM DUAL; /* +--------------------------------------------------+ | CONCAT_WS('-','hello','world','hello','beijing') | +--------------------------------------------------+ | hello-world-hello-beijing | +--------------------------------------------------+ */ #字符串的索引是从1开始的!(Java从0开始的) #INSERT(str, idx, len,replacestr) #将字符串str从第idx位置开始,len个字符长的子串替换为字符串replacestr SELECT INSERT('helloworld',2,3,'aaaaa'),REPLACE('hello','lol','mmm'),REPLACE('hello','lo','mmm') FROM DUAL; /* +----------------------------------+------------------------------+-----------------------------+ | INSERT('helloworld',2,3,'aaaaa') | REPLACE('hello','lol','mmm') | REPLACE('hello','lo','mmm') | +----------------------------------+------------------------------+-----------------------------+ | haaaaaoworld | hello | helmmm | +----------------------------------+------------------------------+-----------------------------+ */ #大小写转换 SELECT UPPER('HelLo'),LOWER('HelLo') FROM DUAL; /* +----------------+----------------+ | UPPER('HelLo') | LOWER('HelLo') | +----------------+----------------+ | HELLO | hello | +----------------+----------------+ */ SELECT last_name,salary FROM employees WHERE LOWER(last_name) = 'King'; /*严格说应该查不到-->但是Mysql大小写不严格 +-----------+----------+ | last_name | salary | +-----------+----------+ | King | 24000.00 | | King | 10000.00 | +-----------+----------+ */ SELECT LEFT('hello',2),RIGHT('hello',3),RIGHT('hello',13) FROM DUAL; /* +-----------------+------------------+-------------------+ | LEFT('hello',2) | RIGHT('hello',3) | RIGHT('hello',13) | +-----------------+------------------+-------------------+ | he | llo | hello | +-----------------+------------------+-------------------+ */ # LPAD:实现右对齐效果 # RPAD:实现左对齐效果 SELECT employee_id,last_name,LPAD(salary,10,'$'),LPAD(salary,10,' ') FROM employees; /* +-------------+-------------+---------------------+---------------------+ | employee_id | last_name | LPAD(salary,10,'$') | LPAD(salary,10,' ') | +-------------+-------------+---------------------+---------------------+ | 100 | King | $$24000.00 | 24000.00 | | 101 | Kochhar | $$17000.00 | 17000.00 | | 102 | De Haan | $$17000.00 | 17000.00 | | 103 | Hunold | $$$9000.00 | 9000.00 | */ #TRIM去掉首尾空格 #LTRIM去掉左侧空格 #TRIM('oo' FROM 'ooheolloo')去掉'oo' SELECT CONCAT('---',LTRIM(' h el lo '),'***'), TRIM('oo' FROM 'ooheolloo') FROM DUAL; /* +-----------------------------------------------+-----------------------------+ | CONCAT('---',LTRIM(' h el lo '),'***') | TRIM('oo' FROM 'ooheolloo') | +-----------------------------------------------+-----------------------------+ | ---h el lo *** | heoll | +-----------------------------------------------+-----------------------------+ */ #REPEAT(str,n):重复n次str #SPACE(n):提供n个空格 #STRCMP:比较字符串大小 SELECT REPEAT('hello',4),LENGTH(SPACE(5)),STRCMP('abc','abe') FROM DUAL; /* +----------------------+------------------+---------------------+ | REPEAT('hello',4) | LENGTH(SPACE(5)) | STRCMP('abc','abe') | +----------------------+------------------+---------------------+ | hellohellohellohello | 5 | -1 | +----------------------+------------------+---------------------+ */ #SUBSTR(str,i,len):截取str中i处起len个字符 #LOCATE('ll','hello')定位‘ll’首次出现的位置 SELECT SUBSTR('hello',2,2),LOCATE('ll','hello'),LOCATE('lll','hello') FROM DUAL; /* +---------------------+----------------------+-----------------------+ | SUBSTR('hello',2,2) | LOCATE('ll','hello') | LOCATE('lll','hello') | +---------------------+----------------------+-----------------------+ | el | 3 | 0 | +---------------------+----------------------+-----------------------+ */ #ELT:返回指定位置的字符串 #FIELD(s,s1,...):返回s在字符列表中首次出现的位置 #FIND_IN_SET(s1,s2):返回s1在s2中首次出现的位置 SELECT ELT(2,'a','b','c','d'),FIELD('mm','gg','jj','mm','dd','mm'), FIND_IN_SET('mm','gg,mm,jj,dd,mm,gg') FROM DUAL; /* +------------------------+--------------------------------------+---------------------------------------+ | ELT(2,'a','b','c','d') | FIELD('mm','gg','jj','mm','dd','mm') | FIND_IN_SET('mm','gg,mm,jj,dd,mm,gg') | +------------------------+--------------------------------------+---------------------------------------+ | b | 3 | 2 | +------------------------+--------------------------------------+---------------------------------------+ */ #NULLIF(s1,s2):字符串s1和s2相等返回NULL,不相等返回s1 SELECT employee_id,NULLIF(LENGTH(first_name),LENGTH(last_name)) "compare" FROM employees; /*姓和名一样长返回NULL +-------------+---------+ | employee_id | compare | +-------------+---------+ | 100 | 6 | | 101 | 5 | | 102 | 3 | | 103 | 9 | | 104 | NULL | */
4 日期和时间函数
4.1 获取日期、时间
#4.1 获取当前日期、时间 SELECT CURDATE(),CURRENT_DATE(),CURTIME(),NOW(),SYSDATE(), UTC_DATE(),UTC_TIME() FROM DUAL; /* +------------+----------------+-----------+---------------------+---------------------+------------+------------+ | CURDATE() | CURRENT_DATE() | CURTIME() | NOW() | SYSDATE() | UTC_DATE() | UTC_TIME() | +------------+----------------+-----------+---------------------+---------------------+------------+------------+ | 2022-02-12 | 2022-02-12 | 18:59:18 | 2022-02-12 18:59:18 | 2022-02-12 18:59:18 | 2022-02-12 | 10:59:18 | +------------+----------------+-----------+---------------------+---------------------+------------+------------+ */ SELECT CURDATE(),CURDATE() + 0,CURTIME() + 0,NOW() + 0 FROM DUAL; /* +------------+---------------+---------------+----------------+ | CURDATE() | CURDATE() + 0 | CURTIME() + 0 | NOW() + 0 | +------------+---------------+---------------+----------------+ | 2022-02-12 | 20220212 | 190103 | 20220212190103 | +------------+---------------+---------------+----------------+ */
4.2 日期与时间戳的转换
#4.2 日期与时间戳的转换 #UNIX_TIMESTAMP(): 以UNIX时间戳(毫秒数)的形式返回当前时间 SELECT UNIX_TIMESTAMP(),UNIX_TIMESTAMP('2021-10-01 12:12:32'), FROM_UNIXTIME(1635173853),FROM_UNIXTIME(1633061552) FROM DUAL; /* +------------------+---------------------------------------+---------------------------+---------------------------+ | UNIX_TIMESTAMP() | UNIX_TIMESTAMP('2021-10-01 12:12:32') | FROM_UNIXTIME(1635173853) | FROM_UNIXTIME(1633061552) | +------------------+---------------------------------------+---------------------------+---------------------------+ | 1644663805 | 1633061552 | 2021-10-25 22:57:33 | 2021-10-01 12:12:32 | +------------------+---------------------------------------+---------------------------+---------------------------+ */
4.3 获取月份、星期、星期数、天数
#4.3 获取月份、星期、星期数、天数等函数 SELECT YEAR(CURDATE()),MONTH(CURDATE()),DAY(CURDATE()), HOUR(CURTIME()),MINUTE(NOW()),SECOND(SYSDATE()) FROM DUAL; /*输出 +-----------------+------------------+----------------+-----------------+---------------+-------------------+ | YEAR(CURDATE()) | MONTH(CURDATE()) | DAY(CURDATE()) | HOUR(CURTIME()) | MINUTE(NOW()) | SECOND(SYSDATE()) | +-----------------+------------------+----------------+-----------------+---------------+-------------------+ | 2022 | 2 | 13 | 2 | 50 | 55 | +-----------------+------------------+----------------+-----------------+---------------+-------------------+ */ #MONTHNAME(date) 返回月份:January,.. #DAYNAME(date) 返回星期几:MONDAY,TUESDAY.....SUNDAY SELECT MONTHNAME('2021-10-26'),DAYNAME('2021-10-26'),WEEKDAY('2021-10-26'), QUARTER(CURDATE()),WEEK(CURDATE()),DAYOFYEAR(NOW()), DAYOFMONTH(NOW()),DAYOFWEEK(NOW()) FROM DUAL; /* +-------------------------+-----------------------+-----------------------+--------------------+-----------------+------------------+-------------------+------------------+ | MONTHNAME('2021-10-26') | DAYNAME('2021-10-26') | WEEKDAY('2021-10-26') | QUARTER(CURDATE()) | WEEK(CURDATE()) | DAYOFYEAR(NOW()) | DAYOFMONTH(NOW()) | DAYOFWEEK(NOW()) | +-------------------------+-----------------------+-----------------------+--------------------+-----------------+------------------+-------------------+------------------+ | October | Tuesday | 1 | 1 | 7 | 44 | 13 | 1 | +-------------------------+-----------------------+-----------------------+--------------------+-----------------+------------------+-------------------+------------------+ */
4.4 日期的操作函数
#EXTRACT(type FROM date) 返回指定日期中特定的部分,type指定返回的值 SELECT EXTRACT(SECOND FROM NOW()),EXTRACT(DAY FROM NOW()), EXTRACT(HOUR_MINUTE FROM NOW()),EXTRACT(QUARTER FROM '2021-05-12') FROM DUAL; /* +----------------------------+-------------------------+---------------------------------+------------------------------------+ | EXTRACT(SECOND FROM NOW()) | EXTRACT(DAY FROM NOW()) | EXTRACT(HOUR_MINUTE FROM NOW()) | EXTRACT(QUARTER FROM '2021-05-12') | +----------------------------+-------------------------+---------------------------------+------------------------------------+ | 18 | 13 | 303 | 2 | +----------------------------+-------------------------+---------------------------------+------------------------------------+ */
4.5 时间和秒钟转换的函数
#4.5 时间和秒钟转换的函数 SELECT TIME_TO_SEC(CURTIME()), SEC_TO_TIME(83355) FROM DUAL; /* +------------------------+--------------------+ | TIME_TO_SEC(CURTIME()) | SEC_TO_TIME(83355) | +------------------------+--------------------+ | 11039 | 23:09:15 | +------------------------+--------------------+ */
4.6 计算日期和时间的函数
第一组:
上述函数中type的取值:
第二组:
#4.6 计算日期和时间的函数 #DATE_ADD(datetime, INTERVAL expr type),ADDDATE(date,INTERVAL expr type) #返回与给定日期时间相差INTERVAL时间段的日期时间 SELECT NOW(),DATE_ADD(NOW(),INTERVAL 1 YEAR), DATE_ADD(NOW(),INTERVAL -1 YEAR), DATE_SUB(NOW(),INTERVAL 1 YEAR) FROM DUAL; /* +---------------------+---------------------------------+----------------------------------+---------------------------------+ | NOW() | DATE_ADD(NOW(),INTERVAL 1 YEAR) | DATE_ADD(NOW(),INTERVAL -1 YEAR) | DATE_SUB(NOW(),INTERVAL 1 YEAR) | +---------------------+---------------------------------+----------------------------------+---------------------------------+ | 2022-02-13 03:04:42 | 2023-02-13 03:04:42 | 2021-02-13 03:04:42 | 2021-02-13 03:04:42 | +---------------------+---------------------------------+----------------------------------+---------------------------------+ */ SELECT DATE_ADD(NOW(), INTERVAL 1 DAY) AS col1,DATE_ADD('2021-10-21 23:32:12',INTERVAL 1 SECOND) AS col2, ADDDATE('2021-10-21 23:32:12',INTERVAL 1 SECOND) AS col3, DATE_ADD('2021-10-21 23:32:12',INTERVAL '1_1' MINUTE_SECOND) AS col4, DATE_ADD(NOW(), INTERVAL -1 YEAR) AS col5, #可以是负数 DATE_ADD(NOW(), INTERVAL '1_1' YEAR_MONTH) AS col6 #需要单引号 FROM DUAL; /*DATE_ADD('2021-10-21 23:32:12',INTERVAL '1_1' MINUTE_SECOND) 加一分一秒 DATE_ADD(NOW(), INTERVAL '1_1' YEAR_MONTH)加一年一个月 +---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+ | col1 | col2 | col3 | col4 | col5 | col6 | +---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+ | 2022-02-14 03:05:23 | 2021-10-21 23:32:13 | 2021-10-21 23:32:13 | 2021-10-21 23:33:13 | 2021-02-13 03:05:23 | 2023-03-13 03:05:23 | +---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+ */ #DATEDIFF(d1,d2)返回时间间隔的天数 SELECT ADDTIME(NOW(),20),SUBTIME(NOW(),30),SUBTIME(NOW(),'1:1:3'),DATEDIFF(NOW(),'2021-10-01'), TIMEDIFF(NOW(),'2021-10-25 22:10:10'),FROM_DAYS(366),TO_DAYS('0000-12-25'), LAST_DAY(NOW()),MAKEDATE(YEAR(NOW()),32),MAKETIME(10,21,23),PERIOD_ADD(20200101010101,10) FROM DUAL; /* +---------------------+---------------------+------------------------+------------------------------+---------------------------------------+----------------+-----------------------+-----------------+--------------------------+--------------------+-------------------------------+ | ADDTIME(NOW(),20) | SUBTIME(NOW(),30) | SUBTIME(NOW(),'1:1:3') | DATEDIFF(NOW(),'2021-10-01') | TIMEDIFF(NOW(),'2021-10-25 22:10:10') | FROM_DAYS(366) | TO_DAYS('0000-12-25') | LAST_DAY(NOW()) | MAKEDATE(YEAR(NOW()),32) | MAKETIME(10,21,23) | PERIOD_ADD(20200101010101,10) | +---------------------+---------------------+------------------------+------------------------------+---------------------------------------+----------------+-----------------------+-----------------+--------------------------+--------------------+-------------------------------+ | 2022-02-13 03:06:21 | 2022-02-13 03:05:31 | 2022-02-13 02:04:58 | 135 | 838:59:59 | 0001-01-01 | 359 | 2022-02-28 | 2022-02-01 | 10:21:23 | 20200101010111 | +---------------------+---------------------+------------------------+------------------------------+---------------------------------------+----------------+-----------------------+-----------------+--------------------------+--------------------+-------------------------------+ 举例:查询 7 天内的新增用户数有多少? SELECT COUNT(*) as num FROM new_user WHERE TO_DAYS(NOW())-TO_DAYS(regist_time)<=7 */
4.7 日期的格式化和解析
上述非GET_FORMAT函数中fmt参数常用的格式符:
GET_FORMAT函数中date_type和format_type参数取值如下:
#4.7 日期的格式化与解析 # 格式化:日期 ---> 字符串 # 解析: 字符串 ----> 日期 #此时我们谈的是日期的显式格式化和解析 #之前,我们接触过隐式的格式化或解析 SELECT * FROM employees WHERE hire_date = '1993-01-13'; /* +-------------+------------+-----------+---------+--------------+------------+--------+----------+----------------+------------+---------------+ | employee_id | first_name | last_name | email | phone_number | hire_date | job_id | salary | commission_pct | manager_id | department_id | +-------------+------------+-----------+---------+--------------+------------+--------+----------+----------------+------------+---------------+ | 102 | Lex | De Haan | LDEHAAN | 515.123.4569 | 1993-01-13 | AD_VP | 17000.00 | NULL | 100 | 90 | +-------------+------------+-----------+---------+--------------+------------+--------+----------+----------------+------------+---------------+ */ #格式化: SELECT DATE_FORMAT(CURDATE(),'%Y-%M-%D'), DATE_FORMAT(NOW(),'%Y-%m-%d'),TIME_FORMAT(CURTIME(),'%h:%i:%S'), DATE_FORMAT(NOW(),'%Y-%M-%D %h:%i:%S %W %w %T %r') FROM DUAL; /* +-----------------------------------+-------------------------------+-----------------------------------+-----------------------------------------------------------+ | DATE_FORMAT(CURDATE(),'%Y-%M-%D') | DATE_FORMAT(NOW(),'%Y-%m-%d') | TIME_FORMAT(CURTIME(),'%h:%i:%S') | DATE_FORMAT(NOW(),'%Y-%M-%D %h:%i:%S %W %w %T %r') | +-----------------------------------+-------------------------------+-----------------------------------+-----------------------------------------------------------+ | 2022-February-13th | 2022-02-13 | 03:07:30 | 2022-February-13th 03:07:30 Sunday 0 03:07:30 03:07:30 AM | +-----------------------------------+-------------------------------+-----------------------------------+-----------------------------------------------------------+ */ #解析:格式化的逆过程 SELECT STR_TO_DATE('2021-October-25th 11:37:30 Monday 1','%Y-%M-%D %h:%i:%S %W %w') FROM DUAL; /* +------------------------------------------------------------------------------+ | STR_TO_DATE('2021-October-25th 11:37:30 Monday 1','%Y-%M-%D %h:%i:%S %W %w') | +------------------------------------------------------------------------------+ | 2021-10-25 11:37:30 | +------------------------------------------------------------------------------+ */ SELECT GET_FORMAT(DATE,'USA') FROM DUAL; /* +------------------------+ | GET_FORMAT(DATE,'USA') | +------------------------+ | %m.%d.%Y | +------------------------+ */ SELECT DATE_FORMAT(CURDATE(),GET_FORMAT(DATE,'USA')) FROM DUAL; /* +-----------------------------------------------+ | DATE_FORMAT(CURDATE(),GET_FORMAT(DATE,'USA')) | +-----------------------------------------------+ | 02.13.2022 | +-----------------------------------------------+ */
5 流程控制函数
流程处理函数可以根据不同的条件,执行不同的处理流程,可以在SQL语句中实现不同的条件选择。
MySQL中的流程处理函数主要包括IF()、IFNULL()和CASE()函数。
#5.流程控制函数 #5.1 IF(value,value1,value2) #如果value的值为TRUE,返回value1,否则返回value2 SELECT last_name,salary,IF(salary >= 6000,'高工资','低工资') "details" FROM employees; /*部分输出 +-------------+----------+-----------+ | last_name | salary | details | +-------------+----------+-----------+ | King | 24000.00 | 高工资 | | Kochhar | 17000.00 | 高工资 | | De Haan | 17000.00 | 高工资 | | Hunold | 9000.00 | 高工资 | | Ernst | 6000.00 | 高工资 | | Austin | 4800.00 | 低工资 | */ SELECT last_name,commission_pct,IF(commission_pct IS NOT NULL,commission_pct,0) "details", salary * 12 * (1 + IF(commission_pct IS NOT NULL,commission_pct,0)) "annual_sal" FROM employees; /* +-------------+----------------+---------+------------+ | last_name | commission_pct | details | annual_sal | +-------------+----------------+---------+------------+ | King | NULL | 0.00 | 288000.00 | | Kochhar | NULL | 0.00 | 204000.00 | | De Haan | NULL | 0.00 | 204000.00 | | Hunold | NULL | 0.00 | 108000.00 | | Ernst | NULL | 0.00 | 72000.00 | */ #5.2 IFNULL(VALUE1,VALUE2):看做是IF(VALUE,VALUE1,VALUE2)的特殊情况 #如果value1不为NULL,返回value1,否则返回value2 SELECT last_name,commission_pct,IFNULL(commission_pct,0) "details" FROM employees; /* +-------------+----------------+---------+ | last_name | commission_pct | details | +-------------+----------------+---------+ | King | NULL | 0.00 | | Kochhar | NULL | 0.00 | | De Haan | NULL | 0.00 | */ #5.3 CASE WHEN ... THEN ...WHEN ... THEN ... ELSE ... END # 类似于java的if ... else if ... else if ... else SELECT last_name,salary,CASE WHEN salary >= 15000 THEN '白骨精' WHEN salary >= 10000 THEN '潜力股' WHEN salary >= 8000 THEN '小屌丝' ELSE '草根' END "details",department_id FROM employees; /*部分输出 +-------------+----------+-----------+---------------+ | last_name | salary | details | department_id | +-------------+----------+-----------+---------------+ | King | 24000.00 | 白骨精 | 90 | | Kochhar | 17000.00 | 白骨精 | 90 | | De Haan | 17000.00 | 白骨精 | 90 | | Hunold | 9000.00 | 小屌丝 | 60 | | Ernst | 6000.00 | 草根 | 60 | | Austin | 4800.00 | 草根 | 60 | | Pataballa | 4800.00 | 草根 | 60 | */ #ELSE可省略,省略时除以上情况外就为NULL SELECT last_name,salary,CASE WHEN salary >= 15000 THEN '白骨精' WHEN salary >= 10000 THEN '潜力股' WHEN salary >= 8000 THEN '小屌丝' END "details" FROM employees; #ELSE可省略,省略时除以上情况外就为NULL /*部分输出 +-------------+----------+-----------+ | last_name | salary | details | +-------------+----------+-----------+ | King | 24000.00 | 白骨精 | | Kochhar | 17000.00 | 白骨精 | | De Haan | 17000.00 | 白骨精 | | Hunold | 9000.00 | 小屌丝 | | Ernst | 6000.00 | NULL | | Austin | 4800.00 | NULL | | Pataballa | 4800.00 | NULL | */ #5.4 CASE ... WHEN ... THEN ... WHEN ... THEN ... ELSE ... END # 类似于java的swich ... case... /* 练习1 查询部门号为 10,20, 30 的员工信息, 若部门号为 10, 则打印其工资的 1.1 倍, 20 号部门, 则打印其工资的 1.2 倍, 30 号部门,打印其工资的 1.3 倍数, 其他部门,打印其工资的 1.4 倍数 */ SELECT employee_id,last_name,department_id,salary,CASE department_id WHEN 10 THEN salary * 1.1 WHEN 20 THEN salary * 1.2 WHEN 30 THEN salary * 1.3 ELSE salary * 1.4 END "details" FROM employees; /*部分输出 +-------------+-------------+---------------+----------+----------+ | employee_id | last_name | department_id | salary | details | +-------------+-------------+---------------+----------+----------+ | 100 | King | 90 | 24000.00 | 33600.00 | | 101 | Kochhar | 90 | 17000.00 | 23800.00 | | 102 | De Haan | 90 | 17000.00 | 23800.00 | | 103 | Hunold | 60 | 9000.00 | 12600.00 | | 104 | Ernst | 60 | 6000.00 | 8400.00 | | 105 | Austin | 60 | 4800.00 | 6720.00 | | 106 | Pataballa | 60 | 4800.00 | 6720.00 | */ /* 练习2 查询部门号为 10,20, 30 的员工信息, 若部门号为 10, 则打印其工资的 1.1 倍, 20 号部门, 则打印其工资的 1.2 倍, 30 号部门打印其工资的 1.3 倍数 */ SELECT employee_id,last_name,department_id,salary,CASE department_id WHEN 10 THEN salary * 1.1 WHEN 20 THEN salary * 1.2 WHEN 30 THEN salary * 1.3 END "details" FROM employees WHERE department_id IN (10,20,30); /*输出 +-------------+------------+---------------+----------+----------+ | employee_id | last_name | department_id | salary | details | +-------------+------------+---------------+----------+----------+ | 200 | Whalen | 10 | 4400.00 | 4840.00 | | 201 | Hartstein | 20 | 13000.00 | 15600.00 | | 202 | Fay | 20 | 6000.00 | 7200.00 | | 114 | Raphaely | 30 | 11000.00 | 14300.00 | | 115 | Khoo | 30 | 3100.00 | 4030.00 | | 116 | Baida | 30 | 2900.00 | 3770.00 | | 117 | Tobias | 30 | 2800.00 | 3640.00 | | 118 | Himuro | 30 | 2600.00 | 3380.00 | | 119 | Colmenares | 30 | 2500.00 | 3250.00 | +-------------+------------+---------------+----------+----------+ */
6 加密与解密函数
加密与解密函数主要用于对数据库中的数据进行加密和解密处理,以防止数据被他人窃取。这些函数在保证数据库安全时非常有用。
可以看到,ENCODE(value,password_seed)函数与DECODE(value,password_seed)函数互为反函数。
#6. 加密与解密的函数 #PASSWORD(str)返回字符串str的加密版本,41位长的字符串。加密结果 不可 #逆 ,常用于用户的密码加密 #MD5(str)返回字符串str的md5加密后的值,也是一种加密方式。若参数为 #NULL,则会返回NULL #SHA(str)从原明文密码str计算并返回加密后的密码字符串,当参数为 #NULL时,返回NULL。 SHA加密算法比MD5更加安全 。 #ENCODE(value,password_seed) 返回使用password_seed作为加密密码加密value #DECODE(value,password_seed) 返回使用password_seed作为加密密码解密value # PASSWORD()在mysql8.0中弃用。 SELECT MD5('mysql'),SHA('mysql'),MD5(MD5('mysql')) FROM DUAL; /*部分输出 +----------------------------------+------------------------------------------+----------------------------------+ | MD5('mysql') | SHA('mysql') | MD5(MD5('mysql')) | +----------------------------------+------------------------------------------+----------------------------------+ | 81c3b080dad537de7e10e0987a4bf52e | f460c882a18c1304d88854e902e11b85d71e7e1b | 9b1c95c962f12d84f57c68e694274783 | +----------------------------------+------------------------------------------+----------------------------------+ */ #ENCODE()\DECODE() 在mysql8.0中弃用。 /* SELECT ENCODE('atguigu','mysql'),DECODE(ENCODE('atguigu','mysql'),'mysql') FROM DUAL; /*5.7输出: +---------------------------+-------------------------------------------+ | ENCODE('atguigu','mysql') | DECODE(ENCODE('atguigu','mysql'),'mysql') | +---------------------------+-------------------------------------------+ | ,敺—+粱 | atguigu | +---------------------------+-------------------------------------------+ */
7 mysql信息函数
MySQL中内置了一些可以查询MySQL信息的函数,这些函数主要用于帮助数据库开发或运维人员更好地对数据库进行维护工作。
#7. MySQL信息函数 #VERSION() 返回当前MySQL的版本号 #CONNECTION_ID() 返回当前MySQL服务器的连接数 #DATABASE(),SCHEMA() 返回MySQL命令行当前所在的数据库 #USER(),CURRENT_USER()、SYSTEM_USER(),SESSION_USER() #返回当前连接MySQL的用户名,返回结果格式为“主机名@用户名” #CHARSET(value) 返回字符串value自变量的字符集 #COLLATION(value) 返回字符串value的比较规则 SELECT VERSION(),CONNECTION_ID(),DATABASE(),SCHEMA(), USER(),CURRENT_USER(),CHARSET('尚硅谷'),COLLATION('尚硅谷') FROM DUAL; /* +-----------+-----------------+------------+-----------+----------------+----------------+----------------------+------------------------+ | VERSION() | CONNECTION_ID() | DATABASE() | SCHEMA() | USER() | CURRENT_USER() | CHARSET('尚硅谷') | COLLATION('尚硅谷') | +-----------+-----------------+------------+-----------+----------------+----------------+----------------------+------------------------+ | 8.0.26 | 8 | atguigudb | atguigudb | root@localhost | root@localhost | utf8mb3 | utf8_general_ci | +-----------+-----------------+------------+-----------+----------------+----------------+----------------------+------------------------+ */
8 其他函数
MySQL中有些函数无法对其进行具体的分类,但是这些函数在MySQL的开发和运维过程中也是不容忽视的。
#FORMAT(value,n)返回对数字value进行格式化后的结果数据。n表示 四舍五入 后保留 #到小数点后n位 SELECT FORMAT(123.125,2),FORMAT(123.125,0),FORMAT(123.125,-2) FROM DUAL; /* +-------------------+-------------------+--------------------+ | FORMAT(123.125,2) | FORMAT(123.125,0) | FORMAT(123.125,-2) | +-------------------+-------------------+--------------------+ | 123.13 | 123 | 123 | +-------------------+-------------------+--------------------+ */ #CONV(value,from,to) 将value的值进行不同进制之间的转换 SELECT CONV(16, 10, 2), CONV(8888,10,16), CONV(NULL, 10, 2) FROM DUAL; /* +-----------------+------------------+-------------------+ | CONV(16, 10, 2) | CONV(8888,10,16) | CONV(NULL, 10, 2) | +-----------------+------------------+-------------------+ | 10000 | 22B8 | NULL | +-----------------+------------------+-------------------+ */ #INET_ATON(ipvalue) 将以点分隔的IP地址转化为一个数字 #INET_NTOA(value) 将数字形式的IP地址转化为以点分隔的IP地址 #以“192.168.1.100”为例,计算方式为192乘以256的3次方,加上168乘以256的2次方,加上1乘以256,再加上100。 SELECT INET_ATON('192.168.1.100'),INET_NTOA(3232235876) FROM DUAL; /* +----------------------------+-----------------------+ | INET_ATON('192.168.1.100') | INET_NTOA(3232235876) | +----------------------------+-----------------------+ | 3232235876 | 192.168.1.100 | +----------------------------+-----------------------+ */ #BENCHMARK(n,expr)将表达式expr重复执行n次。用于测试MySQL处理expr表达式所耗费 #的时间 #BENCHMARK()用于测试表达式的执行效率 SELECT BENCHMARK(100000,MD5('mysql')) FROM DUAL; /* +--------------------------------+ | BENCHMARK(100000,MD5('mysql')) | +--------------------------------+ | 0 | +--------------------------------+ */ # CONVERT():可以实现字符集的转换 #CONVERT(value USING,char_code)将value所使用的字符编码修改为char_code SELECT CHARSET('atguigu'),CHARSET(CONVERT('atguigu' USING 'gbk')) FROM DUAL; /* +--------------------+-----------------------------------------+ | CHARSET('atguigu') | CHARSET(CONVERT('atguigu' USING 'gbk')) | +--------------------+-----------------------------------------+ | gbk | gbk | +--------------------+-----------------------------------------+ */
课后练习
#第07章_单行函数的课后练习 # 1.显示系统时间(注:日期+时间) #只需要掌握一个函数就可以了 SELECT NOW(),SYSDATE(),CURRENT_TIMESTAMP(),LOCALTIME(),LOCALTIMESTAMP() FROM DUAL; /* +---------------------+---------------------+---------------------+---------------------+---------------------+ | NOW() | SYSDATE() | CURRENT_TIMESTAMP() | LOCALTIME() | LOCALTIMESTAMP() | +---------------------+---------------------+---------------------+---------------------+---------------------+ | 2022-02-13 04:23:04 | 2022-02-13 04:23:04 | 2022-02-13 04:23:04 | 2022-02-13 04:23:04 | 2022-02-13 04:23:04 | +---------------------+---------------------+---------------------+---------------------+---------------------+ */ # 2.查询员工号,姓名,工资,以及工资提高百分之20%后的结果(new salary) SELECT employee_id,last_name,salary,salary * 1.2 "new salary" FROM employees; /* +-------------+-------------+----------+------------+ | employee_id | last_name | salary | new salary | +-------------+-------------+----------+------------+ | 100 | King | 24000.00 | 28800.00 | | 101 | Kochhar | 17000.00 | 20400.00 | | 102 | De Haan | 17000.00 | 20400.00 | | 103 | Hunold | 9000.00 | 10800.00 | | 104 | Ernst | 6000.00 | 7200.00 | */ # 3.将员工的姓名按首字母排序,并写出姓名的长度(length) SELECT last_name,LENGTH(last_name) "name_length" FROM employees #order by last_name asc; ORDER BY name_length ASC; /* +-------------+-------------+ | last_name | name_length | +-------------+-------------+ | Gee | 3 | | Seo | 3 | | Lee | 3 | | Fox | 3 | | Fay | 3 | | King | 4 | | Chen | 4 | */ # 4.查询员工id,last_name,salary,并作为一个列输出,别名为OUT_PUT SELECT CONCAT(employee_id,',',last_name,',',salary) "OUT_PUT" FROM employees; /*部分输出 +-------------------------+ | OUT_PUT | +-------------------------+ | 100,King,24000.00 | | 101,Kochhar,17000.00 | | 102,De Haan,17000.00 | | 103,Hunold,9000.00 | | 104,Ernst,6000.00 | | 105,Austin,4800.00 | */ # 5.查询公司各员工工作的年数、工作的天数,并按工作年数的降序排序 SELECT employee_id,DATEDIFF(CURDATE(),hire_date)/365 "worked_years",DATEDIFF(CURDATE(),hire_date) "worked_days", TO_DAYS(CURDATE()) - TO_DAYS(hire_date) "worked_days1" FROM employees ORDER BY worked_years DESC; /*部分输出: +-------------+--------------+-------------+--------------+ | employee_id | worked_years | worked_days | worked_days1 | +-------------+--------------+-------------+--------------+ | 100 | 34.6849 | 12660 | 12660 | | 200 | 34.4329 | 12568 | 12568 | | 101 | 32.4192 | 11833 | 11833 | | 103 | 32.1342 | 11729 | 11729 | | 104 | 30.7562 | 11226 | 11226 | | 102 | 29.1041 | 10623 | 10623 | | 203 | 27.7068 | 10113 | 10113 | */ # 6.查询员工姓名,hire_date , department_id,满足以下条件: #雇用时间在1997年之后,department_id 为80 或 90 或110, commission_pct不为空 SELECT last_name,hire_date,department_id FROM employees WHERE department_id IN (80,90,110) AND commission_pct IS NOT NULL #and hire_date >= '1997-01-01'; #存在着隐式转换 #and date_format(hire_date,'%Y-%m-%d') >= '1997-01-01'; # 显式转换操作,格式化:日期---> 字符串 #and date_format(hire_date,'%Y') >= '1997'; # 显式转换操作,格式化 AND hire_date >= STR_TO_DATE('1997-01-01','%Y-%m-%d');# 显式转换操作,解析:字符串 ----> 日期 /*部分输出: +------------+------------+---------------+ | last_name | hire_date | department_id | +------------+------------+---------------+ | Partners | 1997-01-05 | 80 | | Errazuriz | 1997-03-10 | 80 | | Cambrault | 1999-10-15 | 80 | | Zlotkey | 2000-01-29 | 80 | | Tucker | 1997-01-30 | 80 | | Bernstein | 1997-03-24 | 80 | | Hall | 1997-08-20 | 80 | | Olsen | 1998-03-30 | 80 | */ # 7.查询公司中入职超过10000天的员工姓名、入职时间 SELECT last_name,hire_date FROM employees WHERE DATEDIFF(CURDATE(),hire_date) >= 10000; /*输出: +-----------+------------+ | last_name | hire_date | +-----------+------------+ | King | 1987-06-17 | | Kochhar | 1989-09-21 | | De Haan | 1993-01-13 | | Hunold | 1990-01-03 | | Ernst | 1991-05-21 | | Greenberg | 1994-08-17 | | Faviet | 1994-08-16 | | Whalen | 1987-09-17 | | Mavris | 1994-06-07 | | Baer | 1994-06-07 | | Higgins | 1994-06-07 | | Gietz | 1994-06-07 | +-----------+------------+ */ # 8.做一个查询,产生下面的结果 #<last_name> earns <salary> monthly but wants <salary*3> SELECT CONCAT(last_name,' earns ',TRUNCATE(salary,0), ' monthly but wants ',TRUNCATE(salary * 3,0)) "Dream Salary" FROM employees; /*部分输出 +-----------------------------------------------+ | Dream Salary | +-----------------------------------------------+ | King earns 24000 monthly but wants 72000 | | Kochhar earns 17000 monthly but wants 51000 | | De Haan earns 17000 monthly but wants 51000 | | Hunold earns 9000 monthly but wants 27000 | | Ernst earns 6000 monthly but wants 18000 | | Austin earns 4800 monthly but wants 14400 | | Pataballa earns 4800 monthly but wants 14400 | */ # 9.使用case-when,按照下面的条件: /*job grade AD_PRES A ST_MAN B IT_PROG C SA_REP D ST_CLERK E 产生下面的结果: */ SELECT last_name "Last_name",job_id "Job_id",CASE job_id WHEN 'AD_PRES' THEN 'A' WHEN 'ST_MAN' THEN 'B' WHEN 'IT_PROG' THEN 'C' WHEN 'SA_REP' THEN 'D' WHEN 'ST_CLERK' THEN 'E' END "Grade" FROM employees; /*部分输出 +-------------+------------+-------+ | Last_name | Job_id | Grade | +-------------+------------+-------+ | King | AD_PRES | A | | Kochhar | AD_VP | NULL | | De Haan | AD_VP | NULL | | Hunold | IT_PROG | C | | Ernst | IT_PROG | C | */ SELECT last_name "Last_name",job_id "Job_id",CASE job_id WHEN 'AD_PRES' THEN 'A' WHEN 'ST_MAN' THEN 'B' WHEN 'IT_PROG' THEN 'C' WHEN 'SA_REP' THEN 'D' WHEN 'ST_CLERK' THEN 'E' ELSE "undefined" END "Grade" FROM employees; /*部分输出 +-------------+------------+-----------+ | Last_name | Job_id | Grade | +-------------+------------+-----------+ | King | AD_PRES | A | | Kochhar | AD_VP | undefined | | De Haan | AD_VP | undefined | | Hunold | IT_PROG | C | | Ernst | IT_PROG | C | | Austin | IT_PROG | C | | Pataballa | IT_PROG | C | */