MYSQL 学习笔记(二)

本文详细介绍了MySQL中的字符串函数,包括大小写转换、子串提取、定位、格式化日期等,还涉及算术、聚合及日期时间函数。重点讲解了如何处理空值、计算字符串长度以及日期时间的截取和转换。此外,还提到了一些重要的SQL聚合函数如COUNT、SUM、MAX、MIN和AVG,并展示了日期时间函数如AGE、CURRENT_TIME和DATE_FORMAT的应用。
摘要由CSDN通过智能技术生成

MYSQL 学习笔记二:函数篇

本篇笔记收录整理SQL语句中常用的字符串函数,算术函数,聚合函数以及日期类函数。

DUAL说明

NOTE - when you wish to Select something, but the data is not in a table (as the examples below), you can use a dummy table name called DUAL. This table is only recognised by Mysql as a dummy table, and will never appear as an actual structure. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.

SQL FUNCTIONS

分类

string functions for searching and manipulating strings.

arithmetic functions for performing calculations on numeric values

date functions for reformatting and performing data arithmetic

aggregate functions for calculations on groups of data.


Useful String Functions

  1. 大小写转化
方法说明
LOWER(string)converts upper case alphabetic characters to lower case. Other characters are not affected
UPPER(string)converts lowercase letters in a string to uppercase
  1. 切割字符串
方法说明
**SUBSTR(**string,startposition,length)shows a part of the string starting at the start position of the specified length

案例:

SELECT SUBSTR('ABCDEF',2,3) FROM dual;
# gives BCD

注意这里的起始坐标为1。

  1. 定位子串下标
方法说明
**INSTR(**string1,string2)finds the start position of one string inside another string

案例:

SELECT INSTR('ABCDEF', 'DEF') FROM dual;
# gives 4
  1. 字符串转日期格式
方法说明
str_to_date (string[,format])converts the string to a date. A format may optionally be specified (see later)

案例:

SELECT STR_TO_DATE('12-06-1996', ' %d-%m-%Y ') FROM dual;
  1. 左右侧填充
方法说明
LPAD(str,len,padstr)left pads the string with the specified fill characters to the specified length
RPAD(str,len,padstr)right pads the string with the specified fill characters to the specified length

案例:

SELECT LPAD('hi',4,'??');
# gives  '??hi'
  1. 左右侧/两端去除特定字符
方法说明
**LTRIM(**string)Returns the string str with leading space characters removed
**RTRIM(**string)Returns the string str with trailing space characters removed
TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)Returns a string after removing all prefixes or suffixes from the given string

案例:

SELECT LTRIM('   barbar');
#GIVE 'barbar'

TRIM函数说明

  1. 表达式为空的处理函数
方法说明
IFNULL(expression1, expression2);takes two expressions and if the first expression is not NULL, it returns the first expression. Otherwise, it returns the second expression.

案例:

SELECT *, IFNULL(Comm, 0) FROM EMP;
  1. 字符串长度
方法说明
**LENGTH(**char)length in characters of specified string

注意事项:

you must put single quotes round all data items which are strings.


Arithmetic Functions

基本函数:

方法说明
ABS(numeric)absolute value of the number
MOD(num1, num2)returns the remainder when num1 is divided by num2
ROUND(numeric[,d])rounds the number to d decimal places, the rounding can occur to either side of the decimal point
TRUNCATE(numeric[,d]])truncates to d decimal places
CEIL(numeric)rounds the number up to the nearest integer
FLOOR(numeric)truncates the number to the nearest integer
SQRT(numeric)returns the square root of the number (returns NULL if the number is negative)
TO_CHAR(numeric[,format])converts a number to a character string in the specified format
DATE_FORMAT(date,format)Cut and Paste date_format strings for MySQL

举例:

SELECT ROUND(1234.5678,2) FROM dual;

SELECT TO_CHAR(sysdate(),'DY') FROM dual;
SELECT TO_CHAR(sysdate(),'MONTH') FROM dual;

SELECT DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%s')
SELECT DATE_FORMAT(NOW(),'%m')

注意:

IT IS VERY IMPORTANT TO NOTE THAT IF ANY VARIABLE CONTAINS A NULL VALUE THEN ANY SQL STATEMENT INVOLVING ARITHMETIC WILL IGNORE IT

E.G.

SELECT ABS(SAL-COMM) FROM EMP;

will only produce results for employees who have a non-null commission (or salary)

补充函数:

List of Mathematical Functions

FunctionsExampleOutput
abs ( )abs(-115.36)115.36
cbrt( )cbrt ( 343)7
ceil( )ceil(-53.7 )-53
ceiling( )ceiling(-69.8 )-69
degrees( )degrees( .45)25.783100780887
div( )div( 19 , 3)6
exp( )exp( 2.0 )7.3890560989306502
floor( )floor(-53.6 )-54
ln( )ln( 3.0)1.0986122886681097
log( )log(200.0 )2.3010299956639812
mod( )mod( 38,5)3
pi( )pi( )3.14159265358979
power( )power(7,3 )343
radians( )radians(15.0 )0.261799387799149
random( )random( )
round( )round( 67.456)67
sign( )sign(-14.321 )-1
sqrt( )sqrt(225 )15
trunc( )trunc(67.456 )67

List of Trigonometric Functions

FunctionsSyntaxDescription
acos ( )acos(a)Returns inverse cosine or arc cosine.
asin( )asin(a)Returns inverse sine or arc sine.
atan( )atan(a)Returns inverse tangent or arc tangent.
atan2( )atan2(b,a)Returns inverse tangent of b/a.
cos( )cos(a)Returns cosine.
cot( )cot(a)Returns cotangent.
sin( )sin(a)Returns sine.
tan( )tan(a)Returns tangent.

AGGREGATE OR GROUPING FUNCTIONS

NameDescription
COUNTThis function returns the number or rows or non NULL values for a column
SUMThis function returns the sum of a selected column.
MAXThis function returns the largest value of a specific column.
MINThis function returns the smallest value of a specific column.
AVGThis function returns the average value for a specific column.

注意:

还是注意那个null字段,默认被忽视。

NOTE - because Comm can contain a NULL value, be warned that if it does, SQL cannot evaluate it as an arithmetic expression and will ignore that record. Thus the above will obtain a sum for all Salesmen because they all get commission.

Date and Time Functions

  1. AGE() function

The age() function subtract arguments, producing a “symbolic” result that uses years and months.

Syntax:

age(timestamp, timestamp)
or
age(timestamp)

Return Type: interval

PostgreSQL Version: 9.3

Pictorial Presentation of PostgreSQL AGE() function

Pictorial presentation of postgresql age function

Example 1: PostgreSQL AGE() function

The example below finds the age between two dates specified in the argument.

Code

SELECT age(timestamp '2015-01-15', timestamp '1972-12-28');

Copy

Sample Output:

       age
------------------
 42 years 18 days
(1 row)

Example 2:

The example below finds the age between current date and the date as specified in the argument.

Code

SELECT age(timestamp '2007-10-07');

Sample Output:

          age
-----------------------
 7 years 3 mons 7 days
(1 row)
  1. 当前时间
方法说明
clock_timestamp()shows current date and time (changes during statement execution)
current_date()This function is used to return the current date.
current_time()This function is used to return the current time with a zone.
current_timestamp()This function is used to return the current date and time.
  1. 截取部分信息
方法说明
date_part(text, timestamp)
date_part(text, interval)
The date_part() function is used to return the part of a date and time.

Pictorial presentation of postgresql DATE_PART function

  1. 截断时间
方法说明
date_trunc(text, timestamp)The date_trunc() function is used to truncate to specified precision.

举例:

SELECT date_trunc('hour', timestamp '2002-09-17 19:27:45');

Output:

 2002-09-17 19:00:00
  1. 日期内的单位转化
方法说明
justify_days(interval)This function is used to adjust interval so 30-day time periods are represented as months.
justify_hours(interval)This function is used to adjust interval so 24-hour time periods are represented as days.
justify_interval(interval)This function is used to adjust interval using justify_days and justify_hours, with additional sign adjustments.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0XhcXERj-1633075384578)(https://www.w3resource.com/w3r_images/postgresql-justify_days-function.png)]

Pictorial presentation of PostgreSQL JUSTIFY_INTERVAL() function

  1. 本地时间
方法说明
localtimestampThis function is used to get current date and time (start of current transaction).
now()This function is used to get current date and time (start of current transaction).
statement_timestamp()This function is used to get current date and time (start of current transaction).
timeofday()This function is used to get current date and time (like clock_timestamp, but as a text string).

结果:

        timestamp
-------------------------
 2015-01-15 14:02:56.925
            now
----------------------------
 2015-01-15 14:17:25.919-08
    statement_timestamp
----------------------------
 2015-01-15 14:30:28.322-08
              timeofday
-------------------------------------
 Thu Jan 15 14:47:28.937000 2015 PST
实验指导书内的重要方法
  1. DATE_FORMAT (date,format)
    It presents a date in the specified format

SELECT DATE_FORMAT(now(), ‘%d-%m-%Y’);
See detailed instruction of DATE_FORMAT attached in the following pages

  1. DATE_ADD (start_date, INTERVAL expr unit)
    or start_date + INTERVAL expr unit

It adds an interval to a DATE or DATETIME. Specifically, start_date is a starting DATE or DATETIME value; INTERVAL expr unit is an interval value to be added to the starting date value.

SELECT DATE_ADD(now(), INTERVAL 1 day);

UnitExpression
DAYDAYS
DAY_HOUR‘DAYS HOURS’
DAY_MICROSECOND‘DAYS HOURS:MINUTES:SECONDS.MICROSECONDS’
DAY_MINUTE‘DAYS HOURS:MINUTES’
DAY_SECOND‘DAYS HOURS:MINUTES:SECONDS’
HOURHOURS
HOUR_MICROSECOND‘HOURS:MINUTES:SECONDS.MICROSECONDS’
HOUR_MINUTE‘HOURS:MINUTES’
HOUR_SECOND‘HOURS:MINUTES:SECONDS’
MICROSECONDMICROSECONDS
MINUTEMINUTES
MINUTE_MICROSECOND‘MINUTES:SECONDS.MICROSECONDS’
MINUTE_SECOND‘MINUTES:SECONDS’
MONTHMONTHS
QUARTERQUARTERS
SECONDSECONDS
SECOND_MICROSECOND‘SECONDS.MICROSECONDS’
WEEKWEEKS
YEARYEARS
YEAR_MONTH‘YEARS-MONTHS’
  1. TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

It returns expr1 − expr2 expressed as a value in unit from one date to the other. expr1 and expr2 are date or date-and-time expressions.

select TIMESTAMPDIFF(Day, now(), HIREDATE) from emp;

select TIMESTAMPDIFF(Month, now(), HIREDATE) from emp;

select TIMESTAMPDIFF(Year, now(), HIREDATE) from emp;

  1. LAST_DAY(date)

It takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid.

SELECT LAST_DAY(NOW());

  1. DATE(expr)

It extracts the date part of the date or datetime expression expr.

SELECT DATE(‘2003-12-31 01:02:03’);

Similar functions include Time(), Day(), Month(), Year(), etc.

  1. DATE_FORMAT(date,format)

The DATE_FORMAT function accepts two arguments:

date : is a valid date value that you want to format

format : is a format string that consists of predefined specifiers. Each specifier is preceded by a percentage character ( % ). See the table below for a list of predefined specifiers.

The following are some commonly used date format strings:

DATE_FORMAT stringFormatted date
%Y-%m-%d7/4/2019
%e/%c/%Y4/7/2019
%c/%e/%Y7/4/2019
%d/%m/%Y4/7/2019
%m/%d/%Y7/4/2019
%e/%c/%Y %H:%i4/7/2019 11:20
%c/%e/%Y %H:%i7/4/2019 11:20
%d/%m/%Y %H:%i4/7/2019 11:20
%m/%d/%Y %H:%i7/4/2019 11:20
%e/%c/%Y %T4/7/2019 11:20
%c/%e/%Y %T7/4/2019 11:20
%d/%m/%Y %T4/7/2019 11:20
%m/%d/%Y %T7/4/2019 11:20
%a %D %b %YThu 4th Jul 2019
%a %D %b %Y %H:%iThu 4th Jul 2019 11:20
%a %D %b %Y %TThu 4th Jul 2019 11:20:05
%a %b %e %YThu Jul 4 2019
%a %b %e %Y %H:%iThu Jul 4 2019 11:20
%a %b %e %Y %TThu Jul 4 2019 11:20:05
%W %D %M %YThursday 4th July 2019
%W %D %M %Y %H:%iThursday 4th July 2019 11:20
%W %D %M %Y %TThursday 4th July 2019 11:20:05
%l:%i %p %b %e, %Y7/4/2019 11:20
%M %e, %Y4-Jul-19
%a, %d %b %Y %TThu, 04 Jul 2019 11:20:05
小案例

假如有日期类型的HIREDATE
获取当月的最后一天:LASTDAY(HIREDATE)
获取这周的星期数(1-7):DAYOFWEEK(HIREDATE)
获取这周的星期数(0-6):DATE_FORMAT(HIREDATE,"%w")

参考网址:

https://w3resource.com/PostgreSQL/tutorial.php

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

如果皮卡会coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值