Table of Contents
MYSQL function
1: Aggregation function
2: Mathematical function
2: String function
3:Date function
4: Control flow function
5: Window function
5.1 The serial number function
5.2 Distribution function
Home Database Mysql Tutorial MYSQL function usage example analysis

MYSQL function usage example analysis

May 31, 2023 pm 10:07 PM
mysql

MYSQL function

1: Aggregation function

Aggregation function mainly consists of: count,sum,min,max,avg,group_count()

Focus on group_count( ) function, first group according to the column specified by group by, and separate it with a delimiter, connect the values ​​​​in the same group, and return a string result.

Format: group_count([distinct ]Field name [order by sorting field asc/desc] [separator 'separator'])

Description:

1: Use distinct to exclude duplicate values.
2 : If you need to sort the result values, you can use the order by clause.
3:separator is a string value, the default is a comma.

2: Mathematical function

1:ABS(x) returns the absolute value of x
2:CEIL(x) returns the smallest integer greater than or equal to x (rounded up)
3:FLOOR(x) returns the largest integer less than or equal to x( Round down)
4:GREATEST(expr1,expr2...) returns the maximum value in the list
5:LEAST(expr1,expr2....) returns the minimum value of the list
6 :MAX(x) Returns the maximum value of field x
7:MIN(x) Returns the minimum value of field x
8:MOD(x,y) Returns the remainder after dividing x by y
9: PI() returns pi (3.141593)
10:POW(x,y) returns x raised to the power of y
11:RAND() returns a random number from 0 to 1
12:ROUND(x) returns The nearest integer to x (following rounding)
13:ROUND(x,y) Returns the specified number of decimal places (following rounding)
14:TRUNCATE(x,y) Returns the value x to y decimal places value, (the biggest difference from ROUND is that it will not be rounded)

2: String function

1: char_length(s) returns the string s Number of characters
2:character_length Returns the number of characters of string s
3:concat(s1,s2,s3) Strings s1, s2 and other strings are combined into one string
4:concat_ws( x,s1,s2..) Same as concat(s1,s2,s3) function, but x is added between each string, x can be a separator
5:field(s,s1,s2) return The position of the first string s in the string list (s1, s2..)
6:length() returns the number of bytes. The encoding of utf-8 in mysql is three bytes for a Chinese character
7:ltrim(s) removes the spaces at the beginning of the string s and removes the spaces on the left. rtrim() removes the spaces on the right. trim() removes the spaces on both sides.
8: mid(s,n,len) from the string Intercepting a substring of length len at position n of s is the same as substring(s,n,len)
9:position(s1,in,s) Get the starting position of s1 from string s
10:replcae (s,s1,s2) Replace string s2 with string s1 in string s
11:reverse(s) Reverse the order of string s
12:right(s,n)Return characters The last n characters of string s (n characters taken from the right)
13:strcmp(s1,s2) Compares strings s1 and s2. If s1 and s2 are equal, 0 is returned. If s1>s2, 1 is returned. If s1 is less than s2 returns -1
14:substr(s,start,length) intercepts a substring of length length from the start position of string s
15:ucase(s) upper(s)converts the string to Uppercase
16:lcase(s) lower(s) Convert the string to lowercase

3:Date function

1:unix_timestamp() returns 1970- 01-01 00:00:00 to the current millisecond value
2:unix_timestamp(date_string) Convert the specified date to a millisecond value timestamp
3:from_unixtime(bigint unixtime,string-format) Convert the millisecond value timestamp For the specified format date
4:curdate() returns the current date
5:current_date() returns the current date
6:current_timestamp() returns the current date and time
7:datediff(d1,d2) Calculate the number of days between dates d1>d2 eg:datediff('2022-01-01','2022-02-01')
8:currtime() Return the current time
9:date_format(d, f) Display date d according to the requirements of expression f

4: Control flow function

1:if(expr,v1,v2) If the expression expr is true, return Result v1, otherwise return result v2
2:ifnull(v1,v2) If the value of v1 is null, return v1, otherwise return v2
3:isnull(expression) Determine whether the expression is null
4 :nullif(expr1,expr2) Compares two strings. If the strings expr1 and expr2 are equal, return null, otherwise return expr1
5:case expression when condition1 then result1 when condition2 then result2 else result end represents the start of the case function, and end represents the function End, if condition1 is established, return result1, if condition2 is established, return result2, if all are not established, return result, and when one is established, the following will not be executed.

5: Window function

The window function newly added in mysql8.0 is also called the window function. The non-aggregation window function is relative to the aggregate function. The aggregate function returns a single value (that is, grouping) after calculating a set of data. Non-aggregate functions will only process one row of data at a time. When the window aggregate function calculates the result of a certain field on a row record, the data within the window range can be input into the aggregate function without changing the number of rows

5.1 The serial number function

can realize group sorting and add the serial number

1: row_number()
2: rank()
3: dense_rank()

Writing: select id,...,dense_rank() over(partition by dname order by salary desc) as rn from employee;

Note: Do not add partition by Indicates global sorting

MYSQL function usage example analysis

5.2 Distribution function

1: percent_rank()
Purpose: Each row is based on the formula (rank-1)/(row- 1) Calculate. Rank is the sequence number generated by the rank() function, and row is the total number of rows of records in the current window.
2: cume_dist()
Purpose: Within the group, it is less than or equal to the current rank Number of rows of value/total number of rows in the group
Application scenario: Query the proportion that is less than or equal to the current salary

Writing method: select dname,ename,salary,cume_dist() over(order by salary) as rn1,
cume_dist() over(partition by dname order by salary) as rn2 from employee;

MYSQL function usage example analysis

##5.3 Before and after functions
1: lag(expr,n)

2: lead(expr,n)

Purpose: Return the n lines before or after the current line (lag(exor,n)) The value of expr in row n (lead(expr,n))

Application scenario: Query the difference between the score of the first student and the score of the current student (there can be a field of the previous row of data in the current row) value)

MYSQL function usage example analysis

MYSQL function usage example analysis

5.4 Head and tail functions
1: first_value(expr)

2: last_value(expr)

Purpose: Return the value of the first (first_value(expr)) or the last (last_value(expr)) expr

Application scenario: As of now, sort by date Query the salary of the first and last employee

MYSQL function usage example analysis

5.5 Other functions
1: nth_value(expr,n)

2: ntile(n)

Purpose: Return the value of the nth expr in the window. expr can be an expression or a column name

Application scenario: As of the current salary, display The second or third salary of each employee

MYSQL function usage example analysis

MYSQL function usage example analysis##5.6 Windowed aggregate function

1: sum()
2: avg()

3: min()
4: max()

Writing: select id,.. .,sum(salary) over(partition by dname order by hiredate desc) as rn from employee;

The data of each row of rn is the sum of the current row and the salary of each previous row
If If there is no order by sorting statement, all data in the group will be summed by default


The above is the detailed content of MYSQL function usage example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

See all articles