本节介绍作用于值集合的聚合函数。它们通常与GROUP
BY子句一起使用,将值分组为子集。This section describes aggregate functions that operate on sets
of values. They are often used with a GROUP
BY clause to group values into subsets.
表 14.29 聚合函数Table 14.29 Aggregate Functions
| 名称Name | 说明Description |
|---|---|
AVG() |
返回参数的平均值Return the average value of the argument |
BIT_AND() |
返回按位与Return bitwise AND |
BIT_OR() |
返回按位或Return bitwise OR |
BIT_XOR() |
返回按位异或Return bitwise XOR |
COUNT() |
返回返回的行数Return a count of the number of rows returned |
COUNT(DISTINCT) |
返回不同值的数量Return the count of a number of different values |
GROUP_CONCAT() |
返回一个连接的字符串Return a concatenated string |
JSON_ARRAYAGG() |
将结果集作为单个 JSON 数组返回Return result set as a single JSON array |
JSON_OBJECTAGG() |
将结果集作为单个 JSON 对象返回Return result set as a single JSON object |
MAX() |
返回最大值Return the maximum value |
MIN() |
返回最小值Return the minimum value |
STD() |
返回总体标准差Return the population standard deviation |
STDDEV() |
返回总体标准差Return the population standard deviation |
STDDEV_POP() |
返回总体标准差Return the population standard deviation |
STDDEV_SAMP() |
返回样本标准差Return the sample standard deviation |
SUM() |
返回总和Return the sum |
VAR_POP() |
返回总体标准方差Return the population standard variance |
VAR_SAMP() |
返回样本方差Return the sample variance |
VARIANCE() |
返回总体标准方差Return the population standard variance |
除非另有说明,聚合函数会忽略NULL值。Unless otherwise stated, aggregate functions ignore
NULL values.
如果在不包含GROUP BY子句的语句中使用聚合函数,它相当于对所有行进行分组。更多信息请参见第 14.19.3 节,“MySQL 对 GROUP BY 的处理”。If you use an aggregate function in a statement containing no
GROUP BY clause, it is equivalent to grouping
on all rows. For more information, see
Section 14.19.3, “MySQL Handling of GROUP BY”.
大多数聚合函数可以用作窗口函数。那些可以以这种方式使用的函数,在其语法描述中用 [ 表示,代表一个可选的 over_clause]OVER 子句。over_clause 的描述见 第 14.20.2 节,“窗口函数概念与语法”,其中还包括有关窗口函数使用的其他信息。Most aggregate functions can be used as window functions. Those
that can be used this way are signified in their syntax
description by
[,
representing an optional over_clause]OVER clause.
over_clause is described in
Section 14.20.2, “Window Function Concepts and Syntax”, which also includes
other information about window function usage.
对于数值参数,方差和标准差函数返回一个DOUBLE值。SUM()和AVG()函数对于精确值参数(整数或DECIMAL)返回一个DECIMAL值,对于近似值参数(FLOAT 或 DOUBLE)返回一个DOUBLE值。For numeric arguments, the variance and standard deviation
functions return a DOUBLE value.
The SUM() and
AVG() functions return a
DECIMAL value for exact-value
arguments (integer or DECIMAL),
and a DOUBLE value for
approximate-value arguments
(FLOAT or
DOUBLE).
SUM() 和 AVG() 聚合函数不适用于时间值。(它们会将值转换为数字,丢失第一个非数字字符之后的所有内容。)为解决此问题,请先转换为数字单位,执行聚合操作,然后再转换回时间值。示例:The SUM() and
AVG() aggregate functions do not
work with temporal values. (They convert the values to numbers,
losing everything after the first nonnumeric character.) To work
around this problem, convert to numeric units, perform the
aggregate operation, and convert back to a temporal value.
Examples:
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROMtbl_name; SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROMtbl_name;
像 SUM() 或 AVG() 这样的函数,如果期望的参数是数字,将在必要时将参数转换为数字。对于 SET 或 ENUM 值,转换操作会使用其底层的数值。Functions such as SUM() or
AVG() that expect a numeric
argument cast the argument to a number if necessary. For
SET or
ENUM values, the cast operation
causes the underlying numeric value to be used.
BIT_AND()、BIT_OR() 和 BIT_XOR() 聚合函数执行位运算。The BIT_AND(),
BIT_OR(), and
BIT_XOR() aggregate functions
perform bit operations.
MySQL 位函数和运算符允许二进制字符串类型的参数(BINARY、VARBINARY 和 BLOB 类型)并返回同类型的值,这使得它们能够使用大于 64 位的参数并生成返回值。关于位操作的参数求值和结果类型的讨论,请参阅第 14.12 节,“位函数和运算符”中的引言讨论。MySQL bit functions and operators permit binary string type
arguments (BINARY,
VARBINARY, and the
BLOB types) and return a value of
like type, which enables them to take arguments and produce
return values larger than 64 bits. For discussion about argument
evaluation and result types for bit operations, see the
introductory discussion in Section 14.12, “Bit Functions and Operators”.
AVG([DISTINCT]expr) [over_clause]返回
的平均值。可以使用exprDISTINCT选项来返回expr的不同值的平均值。Returns the average value of. TheexprDISTINCToption can be used to return the average of the distinct values ofexpr.如果没有匹配的行,
AVG()返回NULL。如果expr为NULL,该函数也返回NULL。If there are no matching rows,AVG()returnsNULL. The function also returnsNULLifexprisNULL.如果存在
over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT.mysql>
SELECT student_name, AVG(test_score)FROM studentGROUP BY student_name;返回
expr中所有位的按位AND。Returns the bitwiseANDof all bits inexpr.结果类型取决于函数参数值是作为二进制字符串还是数字来计算:The result type depends on whether the function argument values are evaluated as binary strings or numbers:
二进制字符串求值发生在参数值具有二进制字符串类型,并且参数不是十六进制字面量、位字面量或
NULL字面量时。否则进行数值求值,并在必要时将参数值转换为无符号 64 位整数。Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, orNULLliteral. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.二进制字符串求值会生成与参数值长度相同的二进制字符串。如果参数值长度不相等,会发生
ER_INVALID_BITWISE_OPERANDS_SIZE错误。如果参数大小超过 511 字节,会发生ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE错误。数值求值会生成一个无符号 64 位整数。Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, anER_INVALID_BITWISE_OPERANDS_SIZEerror occurs. If the argument size exceeds 511 bytes, anER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZEerror occurs. Numeric evaluation produces an unsigned 64-bit integer.
如果没有匹配的行,
BIT_AND()会返回一个中性值(所有位都设为 1),该中性值的长度与参数值的长度相同。If there are no matching rows,BIT_AND()returns a neutral value (all bits set to 1) having the same length as the argument values.NULL值不会影响结果,除非所有值都是NULL。在这种情况下,结果是一个与参数值长度相同的中性值。NULLvalues do not affect the result unless all values areNULL. In that case, the result is a neutral value having the same length as the argument values.有关参数求值和结果类型的更多信息,请参阅 第 14.12 节,“位函数和运算符” 中的介绍讨论。For more information discussion about argument evaluation and result types, see the introductory discussion in Section 14.12, “Bit Functions and Operators”.
如果从 mysql 客户端内部调用
BIT_AND(),则二进制字符串结果将根据--binary-as-hex的值以十六进制表示。有关该选项的更多信息,请参阅 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfBIT_AND()is invoked from within the mysql client, binary string results display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.返回
expr中所有位的按位OR结果。Returns the bitwiseORof all bits inexpr.结果类型取决于函数参数值是作为二进制字符串还是数字来计算:The result type depends on whether the function argument values are evaluated as binary strings or numbers:
二进制字符串求值发生在参数值具有二进制字符串类型,并且参数不是十六进制字面量、位字面量或
NULL字面量时。否则进行数值求值,并在必要时将参数值转换为无符号 64 位整数。Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, orNULLliteral. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.二进制字符串求值会生成与参数值长度相同的二进制字符串。如果参数值长度不相等,会发生
ER_INVALID_BITWISE_OPERANDS_SIZE错误。如果参数大小超过 511 字节,会发生ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE错误。数值求值会生成一个无符号 64 位整数。Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, anER_INVALID_BITWISE_OPERANDS_SIZEerror occurs. If the argument size exceeds 511 bytes, anER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZEerror occurs. Numeric evaluation produces an unsigned 64-bit integer.
如果没有匹配的行,
BIT_OR()返回一个中性值(所有位都为 0),其长度与参数值相同。If there are no matching rows,BIT_OR()returns a neutral value (all bits set to 0) having the same length as the argument values.NULL值不会影响结果,除非所有值都是NULL。在这种情况下,结果是一个与参数值长度相同的中性值。NULLvalues do not affect the result unless all values areNULL. In that case, the result is a neutral value having the same length as the argument values.有关参数求值和结果类型的更多信息,请参阅 第 14.12 节,“位函数和运算符” 中的介绍讨论。For more information discussion about argument evaluation and result types, see the introductory discussion in Section 14.12, “Bit Functions and Operators”.
如果从 mysql 客户端中调用
BIT_OR(),二进制字符串结果将根据--binary-as-hex的值以十六进制表示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfBIT_OR()is invoked from within the mysql client, binary string results display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.返回
expr中所有位的按位XOR。Returns the bitwiseXORof all bits inexpr.结果类型取决于函数参数值是作为二进制字符串还是数字来计算:The result type depends on whether the function argument values are evaluated as binary strings or numbers:
二进制字符串求值发生在参数值具有二进制字符串类型,并且参数不是十六进制字面量、位字面量或
NULL字面量时。否则进行数值求值,并在必要时将参数值转换为无符号 64 位整数。Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, orNULLliteral. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.二进制字符串求值会生成与参数值长度相同的二进制字符串。如果参数值长度不相等,会发生
ER_INVALID_BITWISE_OPERANDS_SIZE错误。如果参数大小超过 511 字节,会发生ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE错误。数值求值会生成一个无符号 64 位整数。Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, anER_INVALID_BITWISE_OPERANDS_SIZEerror occurs. If the argument size exceeds 511 bytes, anER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZEerror occurs. Numeric evaluation produces an unsigned 64-bit integer.
如果没有匹配的行,
BIT_XOR()将返回一个中性值(所有位都为 0),长度与参数值相同。If there are no matching rows,BIT_XOR()returns a neutral value (all bits set to 0) having the same length as the argument values.NULL值不会影响结果,除非所有值都是NULL。在这种情况下,结果是一个与参数值长度相同的中性值。NULLvalues do not affect the result unless all values areNULL. In that case, the result is a neutral value having the same length as the argument values.有关参数求值和结果类型的更多信息,请参阅 第 14.12 节,“位函数和运算符” 中的介绍讨论。For more information discussion about argument evaluation and result types, see the introductory discussion in Section 14.12, “Bit Functions and Operators”.
如果
BIT_XOR()在 mysql 客户端中调用,二进制字符串结果将根据--binary-as-hex的值以十六进制显示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — The MySQL 命令行客户端”。IfBIT_XOR()is invoked from within the mysql client, binary string results display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.返回通过
SELECT语句检索的行中expr的非NULL值的数量。结果是一个BIGINT值。Returns a count of the number of non-NULLvalues ofexprin the rows retrieved by aSELECTstatement. The result is aBIGINTvalue.如果没有匹配的行,
COUNT()返回0。COUNT(NULL)返回 0。If there are no matching rows,COUNT()returns0.COUNT(NULL)returns 0.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.mysql>
SELECT student.student_name,COUNT(*)FROM student,courseWHERE student.student_id=course.student_idGROUP BY student_name;COUNT(*)有些不同,因为它返回检索到的行数,无论这些行是否包含NULL值。COUNT(*)is somewhat different in that it returns a count of the number of rows retrieved, whether or not they containNULLvalues.对于像
InnoDB这样的事务存储引擎,存储精确的行数是有问题的。可能有多个事务同时进行,每个事务都可能影响计数。For transactional storage engines such asInnoDB, storing an exact row count is problematic. Multiple transactions may be occurring at the same time, each of which may affect the count.InnoDBdoes not keep an internal count of rows in a table because concurrent transactions might “第 13.4.4 节,“几何体的正确性和有效性”” different numbers of rows at the same time. Consequently,SELECT COUNT(*)statements only count rows visible to the current transaction.InnoDBdoes not keep an internal count of rows in a table because concurrent transactions might “see” different numbers of rows at the same time. Consequently,SELECT COUNT(*)statements only count rows visible to the current transaction.SELECT COUNT(*) FROM tbl_name对InnoDB表的查询性能在没有额外条件(如WHERE或GROUP BY)时,对于单线程工作负载是优化的。SELECT COUNT(*) FROMquery performance fortbl_nameInnoDBtables is optimized for single-threaded workloads if there are no extra clauses such asWHEREorGROUP BY.InnoDB处理SELECT COUNT(*)语句的方法是遍历最小的可用二级索引,除非索引或优化器提示指示优化器使用不同的索引。如果不存在二级索引,InnoDB就通过扫描聚簇索引来处理SELECT COUNT(*)语句。InnoDBprocessesSELECT COUNT(*)statements by traversing the smallest available secondary index unless an index or optimizer hint directs the optimizer to use a different index. If a secondary index is not present,InnoDBprocessesSELECT COUNT(*)statements by scanning the clustered index.如果索引记录未完全在缓冲池中,处理
SELECT COUNT(*)语句需要一些时间。为了更快地计数,可以创建一个计数表,并让您的应用程序根据它执行的插入和删除来更新它。然而,在数千个并发事务同时对同一个计数表进行更新的情况下,这种方法可能无法很好地扩展。如果大约的行数就足够了,可以使用SHOW TABLE STATUS。Processing ofSELECT COUNT(*)statements takes some time if index records are not entirely in the buffer pool. For a faster count, create a counter table and let your application update it according to the inserts and deletes it does. However, this method may not scale well in situations where thousands of concurrent transactions are initiating updates to the same counter table. If an approximate row count is sufficient, useSHOW TABLE STATUS.InnoDB对SELECT COUNT(*)和SELECT COUNT(1)操作的处理方式相同。性能没有差异。InnoDBhandlesSELECT COUNT(*)andSELECT COUNT(1)operations in the same way. There is no performance difference.对于
MyISAM表,如果COUNT(*)用于从一个表中检索数据、未检索其他列且没有WHERE子句的SELECT,则会被优化为非常快速地返回。例如:ForMyISAMtables,COUNT(*)is optimized to return very quickly if theSELECTretrieves from one table, no other columns are retrieved, and there is noWHEREclause. For example:mysql>
SELECT COUNT(*) FROM student;该优化仅适用于
MyISAM表,因为该存储引擎存储了精确的行数,可以非常快速地访问。COUNT(1)只有在第一列定义为NOT NULL时,才适用相同的优化。This optimization only applies toMyISAMtables, because an exact row count is stored for this storage engine and can be accessed very quickly.COUNT(1)is only subject to the same optimization if the first column is defined asNOT NULL.COUNT(DISTINCTexpr,[expr...])返回不同的非
NULLexpr值的行数计数。Returns a count of the number of rows with different non-NULLexprvalues.如果没有匹配的行,
COUNT(DISTINCT)返回0。If there are no matching rows,COUNT(DISTINCT)returns0.mysql>
SELECT COUNT(DISTINCT results) FROM student;在 MySQL 中,你可以通过提供一个表达式列表来获得不包含
NULL的不同表达式组合的数量。在标准 SQL 中,你必须在COUNT(DISTINCT ...)内对所有表达式进行连接。In MySQL, you can obtain the number of distinct expression combinations that do not containNULLby giving a list of expressions. In standard SQL, you would have to do a concatenation of all expressions insideCOUNT(DISTINCT ...).此函数返回一个字符串结果,该结果是一个组中非
NULL值的连接。如果没有非NULL值,则返回NULL。完整语法如下:This function returns a string result with the concatenated non-NULLvalues from a group. It returnsNULLif there are no non-NULLvalues. The full syntax is as follows:GROUP_CONCAT([DISTINCT]
expr[,expr...] [ORDER BY {unsigned_integer|col_name|expr} [ASC | DESC] [,col_name...]] [SEPARATORstr_val])mysql>
SELECT student_name,GROUP_CONCAT(test_score)FROM studentGROUP BY student_name;或者:Or:
mysql>
SELECT student_name,GROUP_CONCAT(DISTINCT test_scoreORDER BY test_score DESC SEPARATOR ' ')FROM studentGROUP BY student_name;在 MySQL 中,您可以获取表达式组合的连接值。要消除重复值,请使用
DISTINCT子句。要对结果中的值进行排序,请使用ORDER BY子句。要进行反向排序,请在ORDER BY子句中您要排序的列名后添加DESC(降序)关键字。默认是升序;也可以使用ASC关键字显式指定。组中值的默认分隔符是逗号(,)。要显式指定分隔符,请使用SEPARATOR,后跟应插入组值之间的字符串字面值。要完全消除分隔符,请指定SEPARATOR ''。In MySQL, you can get the concatenated values of expression combinations. To eliminate duplicate values, use theDISTINCTclause. To sort values in the result, use theORDER BYclause. To sort in reverse order, add theDESC(descending) keyword to the name of the column you are sorting by in theORDER BYclause. The default is ascending order; this may be specified explicitly using theASCkeyword. The default separator between values in a group is comma (,). To specify a separator explicitly, useSEPARATORfollowed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specifySEPARATOR ''.结果被截断到由
group_concat_max_len系统变量指定的最大长度,其默认值为 1024。该值可以设置得更高,尽管返回值的有效最大长度受max_allowed_packet值的限制。在运行时更改group_concat_max_len值的语法如下,其中val是无符号整数:The result is truncated to the maximum length that is given by thegroup_concat_max_lensystem variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value ofmax_allowed_packet. The syntax to change the value ofgroup_concat_max_lenat runtime is as follows, wherevalis an unsigned integer:SET [GLOBAL | SESSION] group_concat_max_len =
val;Important在为
group_concat_max_len设置值时,请考虑以下内容:When setting the value forgroup_concat_max_len, consider the following:估算
GROUP_CONCAT()输出所需的最大长度,并相应地设置该值。Estimate the maximum length required forGROUP_CONCAT()output and set the value accordingly.将值设置得过高可能会对性能产生负面影响,并导致内存不足(OOM)错误。Setting the value excessively high can negatively affect performance and lead to out-of-memory (OOM) errors.
在 MySQL HeatWave 中,最大列长度为 4 MB,因此设置高于此值会导致输出被截断。为避免这种情况,请将值设置在 4 MB 以下。In MySQL HeatWave, the maximum column length is 4 MB, so setting a value higher than this causes the output to be truncated. To avoid this, set a value under 4 MB.
返回值是非二进制或二进制字符串,取决于参数是非二进制还是二进制字符串。结果类型是
TEXT或BLOB,除非group_concat_max_len小于或等于 512,在这种情况下,结果类型是VARCHAR或VARBINARY。The return value is a nonbinary or binary string, depending on whether the arguments are nonbinary or binary strings. The result type isTEXTorBLOBunlessgroup_concat_max_lenis less than or equal to 512, in which case the result type isVARCHARorVARBINARY.如果从 mysql 客户端内部调用
GROUP_CONCAT(),二进制字符串结果将根据--binary-as-hex的值以十六进制表示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfGROUP_CONCAT()is invoked from within the mysql client, binary string results display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.另请参见
CONCAT()和CONCAT_WS():第 14.8 节,“字符串函数和运算符”。See alsoCONCAT()andCONCAT_WS(): Section 14.8, “String Functions and Operators”.JSON_ARRAYAGG(col_or_expr) [over_clause]将结果集聚合为单个
JSON数组,其元素由各行组成。该数组中元素的顺序未定义。该函数作用于列或求值为单个值的表达式。如果结果不包含行或发生错误,则返回NULL。如果col_or_expr为NULL,函数将返回包含 JSON[null]元素的数组。Aggregates a result set as a singleJSONarray whose elements consist of the rows. The order of elements in this array is undefined. The function acts on a column or an expression that evaluates to a single value. ReturnsNULLif the result contains no rows, or in the event of an error. Ifcol_or_exprisNULL, the function returns an array of JSON[null]elements.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.mysql>
SELECT o_id, attribute, value FROM t3;+------+-----------+-------+ | o_id | attribute | value | +------+-----------+-------+ | 2 | color | red | | 2 | fabric | silk | | 3 | color | green | | 3 | shape | square| +------+-----------+-------+ 4 rows in set (0.00 sec) mysql>SELECT o_id, JSON_ARRAYAGG(attribute) AS attributes->FROM t3 GROUP BY o_id;+------+---------------------+ | o_id | attributes | +------+---------------------+ | 2 | ["color", "fabric"] | | 3 | ["color", "shape"] | +------+---------------------+ 2 rows in set (0.00 sec)JSON_OBJECTAGG(key,value) [over_clause]接受两个列名或表达式作为参数,第一个用作键,第二个用作值,并返回包含键值对的 JSON 对象。如果结果不包含任何行,或发生错误,则返回
NULL。如果任意键名为NULL或参数数量不等于 2,则会发生错误。Takes two column names or expressions as arguments, the first of these being used as a key and the second as a value, and returns a JSON object containing key-value pairs. ReturnsNULLif the result contains no rows, or in the event of an error. An error occurs if any key name isNULLor the number of arguments is not equal to 2.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.mysql>
SELECT o_id, attribute, value FROM t3;+------+-----------+-------+ | o_id | attribute | value | +------+-----------+-------+ | 2 | color | red | | 2 | fabric | silk | | 3 | color | green | | 3 | shape | square| +------+-----------+-------+ 4 rows in set (0.00 sec) mysql>SELECT o_id, JSON_OBJECTAGG(attribute, value)->FROM t3 GROUP BY o_id;+------+---------------------------------------+ | o_id | JSON_OBJECTAGG(attribute, value) | +------+---------------------------------------+ | 2 | {"color": "red", "fabric": "silk"} | | 3 | {"color": "green", "shape": "square"} | +------+---------------------------------------+ 2 rows in set (0.00 sec)重复键处理。 当此函数的结果被标准化时,具有重复键的值将被丢弃。遵循 MySQL
JSON数据类型规范,该规范不允许重复键,在返回的对象中只使用最后遇到的值作为该键的值(“最后的重复键胜出”)。这意味着,对SELECT的列使用此函数的结果可能取决于返回行的顺序,而返回顺序并不保证固定。Duplicate key handling. When the result of this function is normalized, values having duplicate keys are discarded. In keeping with the MySQLJSONdata type specification that does not permit duplicate keys, only the last value encountered is used with that key in the returned object (“last duplicate key wins”). This means that the result of using this function on columns from aSELECTcan depend on the order in which the rows are returned, which is not guaranteed.当用作窗口函数时,如果框架内存在重复键,则结果中仅包含键的最后一个值。如果
ORDER BY规范保证值具有特定顺序,则框架中最后一行的键值是确定的。如果没有,则键的结果值是不确定的。When used as a window function, if there are duplicate keys within a frame, only the last value for the key is present in the result. The value for the key from the last row in the frame is deterministic if theORDER BYspecification guarantees that the values have a specific order. If not, the resulting value of the key is nondeterministic.请考虑以下内容:Consider the following:
mysql>
CREATE TABLE t(c VARCHAR(10), i INT);Query OK, 0 rows affected (0.33 sec) mysql>INSERT INTO t VALUES ('key', 3), ('key', 4), ('key', 5);Query OK, 3 rows affected (0.10 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql>SELECT c, i FROM t;+------+------+ | c | i | +------+------+ | key | 3 | | key | 4 | | key | 5 | +------+------+ 3 rows in set (0.00 sec) mysql>SELECT JSON_OBJECTAGG(c, i) FROM t;+----------------------+ | JSON_OBJECTAGG(c, i) | +----------------------+ | {"key": 5} | +----------------------+ 1 row in set (0.00 sec) mysql>DELETE FROM t;Query OK, 3 rows affected (0.08 sec) mysql>INSERT INTO t VALUES ('key', 3), ('key', 5), ('key', 4);Query OK, 3 rows affected (0.06 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql>SELECT c, i FROM t;+------+------+ | c | i | +------+------+ | key | 3 | | key | 5 | | key | 4 | +------+------+ 3 rows in set (0.00 sec) mysql>SELECT JSON_OBJECTAGG(c, i) FROM t;+----------------------+ | JSON_OBJECTAGG(c, i) | +----------------------+ | {"key": 4} | +----------------------+ 1 row in set (0.00 sec)从上一次查询中选择的键是非确定性的。如果查询没有使用
GROUP BY(通常会自行强制排序)并且您更喜欢特定的键排序,可以通过包含带有ORDER BY指定的OVER子句,将JSON_OBJECTAGG()作为窗口函数调用,以对帧行施加特定顺序。以下示例展示了在具有不同帧规格时,使用和不使用ORDER BY的情况。The key chosen from the last query is nondeterministic. If the query does not useGROUP BY(which usually imposes its own ordering regardless) and you prefer a particular key ordering, you can invokeJSON_OBJECTAGG()as a window function by including anOVERclause with anORDER BYspecification to impose a particular order on frame rows. The following examples show what happens with and withoutORDER BYfor a few different frame specifications.没有
ORDER BY时,帧为整个分区:WithoutORDER BY, the frame is the entire partition:mysql>
SELECT JSON_OBJECTAGG(c, i)OVER () AS json_object FROM t;+-------------+ | json_object | +-------------+ | {"key": 4} | | {"key": 4} | | {"key": 4} | +-------------+使用
ORDER BY时,帧默认是RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW(在升序和降序中均适用):WithORDER BY, where the frame is the default ofRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW(in both ascending and descending order):mysql>
SELECT JSON_OBJECTAGG(c, i)OVER (ORDER BY i) AS json_object FROM t;+-------------+ | json_object | +-------------+ | {"key": 3} | | {"key": 4} | | {"key": 5} | +-------------+ mysql>SELECT JSON_OBJECTAGG(c, i)OVER (ORDER BY i DESC) AS json_object FROM t;+-------------+ | json_object | +-------------+ | {"key": 5} | | {"key": 4} | | {"key": 3} | +-------------+使用
ORDER BY并明确指定整个分区的帧:WithORDER BYand an explicit frame of the entire partition:mysql>
SELECT JSON_OBJECTAGG(c, i)OVER (ORDER BY iROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)AS json_objectFROM t;+-------------+ | json_object | +-------------+ | {"key": 5} | | {"key": 5} | | {"key": 5} | +-------------+要返回特定的键值(例如最小值或最大值),请在相应的查询中包含
LIMIT子句。例如:To return a particular key value (such as the smallest or largest), include aLIMITclause in the appropriate query. For example:mysql>
SELECT JSON_OBJECTAGG(c, i)OVER (ORDER BY i) AS json_object FROM t LIMIT 1;+-------------+ | json_object | +-------------+ | {"key": 3} | +-------------+ mysql>SELECT JSON_OBJECTAGG(c, i)OVER (ORDER BY i DESC) AS json_object FROM t LIMIT 1;+-------------+ | json_object | +-------------+ | {"key": 5} | +-------------+请参阅 JSON 值的规范化、合并和自动包装,获取更多信息和示例。See Normalization, Merging, and Autowrapping of JSON Values, for additional information and examples.
MAX([DISTINCT]expr) [over_clause]返回
expr的最大值。MAX()可以接受字符串参数;在这种情况下,它返回最大字符串值。参见 第 10.3.1 节,“MySQL 如何使用索引”。DISTINCT关键字可以用来查找expr的不同值的最大值,但这与省略DISTINCT得到的结果相同。Returns the maximum value ofexpr.MAX()may take a string argument; in such cases, it returns the maximum string value. See Section 10.3.1, “How MySQL Uses Indexes”. TheDISTINCTkeyword can be used to find the maximum of the distinct values ofexpr, however, this produces the same result as omittingDISTINCT.如果没有匹配的行,或者
expr为NULL,MAX()返回NULL。If there are no matching rows, or ifexprisNULL,MAX()returnsNULL.如果存在
over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT.mysql>
SELECT student_name, MIN(test_score), MAX(test_score)FROM studentGROUP BY student_name;对于
MAX(),MySQL 当前比较ENUM和SET列时,是按它们的字符串值进行比较,而不是按字符串在集合中的相对位置进行比较。这与ORDER BY比较它们的方式不同。ForMAX(), MySQL currently comparesENUMandSETcolumns by their string value rather than by the string's relative position in the set. This differs from howORDER BYcompares them.MIN([DISTINCT]expr) [over_clause]返回
expr的最小值。MIN()可以接受字符串参数;在这种情况下,它返回最小的字符串值。参见 第 10.3.1 节,“MySQL 如何使用索引”。DISTINCT关键字可以用于查找expr不同值的最小值,但这与省略DISTINCT得到的结果相同。Returns the minimum value ofexpr.MIN()may take a string argument; in such cases, it returns the minimum string value. See Section 10.3.1, “How MySQL Uses Indexes”. TheDISTINCTkeyword can be used to find the minimum of the distinct values ofexpr, however, this produces the same result as omittingDISTINCT.如果没有匹配的行,或者
expr为NULL,MIN()返回NULL。If there are no matching rows, or ifexprisNULL,MIN()returnsNULL.如果存在
over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT.mysql>
SELECT student_name, MIN(test_score), MAX(test_score)FROM studentGROUP BY student_name;对于
MIN(),MySQL 当前通过字符串值比较ENUM和SET列,而不是通过字符串在集合中的相对位置进行比较。这与ORDER BY对它们的比较方式不同。ForMIN(), MySQL currently comparesENUMandSETcolumns by their string value rather than by the string's relative position in the set. This differs from howORDER BYcompares them.返回
expr的总体标准差。STD()是标准 SQL 函数STDDEV_POP()的同义词,作为 MySQL 扩展提供。Returns the population standard deviation ofexpr.STD()is a synonym for the standard SQL functionSTDDEV_POP(), provided as a MySQL extension.如果没有匹配的行,或者
expr为NULL,STD()返回NULL。If there are no matching rows, or ifexprisNULL,STD()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.返回
expr的总体标准差。STDDEV()是标准 SQL 函数STDDEV_POP()的同义词,为了与 Oracle 兼容而提供。Returns the population standard deviation ofexpr.STDDEV()is a synonym for the standard SQL functionSTDDEV_POP(), provided for compatibility with Oracle.如果没有匹配的行,或者
expr为NULL,STDDEV()将返回NULL。If there are no matching rows, or ifexprisNULL,STDDEV()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.STDDEV_POP(expr) [over_clause]返回
expr的总体标准差(即VAR_POP()的平方根)。你也可以使用STD()或STDDEV(),它们功能相同,但不是标准 SQL。Returns the population standard deviation ofexpr(the square root ofVAR_POP()). You can also useSTD()orSTDDEV(), which are equivalent but not standard SQL.如果没有匹配的行,或者
expr为NULL,STDDEV_POP()将返回NULL。If there are no matching rows, or ifexprisNULL,STDDEV_POP()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.STDDEV_SAMP(expr) [over_clause]返回
expr的样本标准差(即VAR_SAMP()的平方根)。Returns the sample standard deviation ofexpr(the square root ofVAR_SAMP().如果没有匹配的行,或者
expr为NULL,STDDEV_SAMP()将返回NULL。If there are no matching rows, or ifexprisNULL,STDDEV_SAMP()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.SUM([DISTINCT]expr) [over_clause]返回
expr的总和。如果返回集没有行,SUM()返回NULL。DISTINCT关键字可用于仅对expr的不同值求和。Returns the sum ofexpr. If the return set has no rows,SUM()returnsNULL. TheDISTINCTkeyword can be used to sum only the distinct values ofexpr.如果没有匹配的行,或者
expr是NULL,SUM()将返回NULL。If there are no matching rows, or ifexprisNULL,SUM()returnsNULL.如果存在
over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT.返回
expr的总体标准方差。它将行视为整个总体,而不是样本,因此分母是行数。你也可以使用VARIANCE(),它等价,但不是标准 SQL。Returns the population standard variance ofexpr. It considers rows as the whole population, not as a sample, so it has the number of rows as the denominator. You can also useVARIANCE(), which is equivalent but is not standard SQL.如果没有匹配的行,或者
expr为NULL,VAR_POP()将返回NULL。If there are no matching rows, or ifexprisNULL,VAR_POP()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.返回
expr的样本方差。也就是说,分母是行数减一。Returns the sample variance ofexpr. That is, the denominator is the number of rows minus one.如果没有匹配的行,或者
expr为NULL,VAR_SAMP()将返回NULL。If there are no matching rows, or ifexprisNULL,VAR_SAMP()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.返回
expr的总体标准方差。VARIANCE()是标准 SQL 函数VAR_POP()的同义词,由 MySQL 扩展提供。Returns the population standard variance ofexpr.VARIANCE()is a synonym for the standard SQL functionVAR_POP(), provided as a MySQL extension.如果没有匹配的行,或者
expr为NULL,VARIANCE()将返回NULL。If there are no matching rows, or ifexprisNULL,VARIANCE()returnsNULL.如果存在
over_clause,此函数作为窗口函数执行。over_clause的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function ifover_clauseis present.over_clauseis as described in Section 14.20.2, “Window Function Concepts and Syntax”.