8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

正文为中文,英文原文默认隐藏。点击任意中文段落即可展开 / 收起对应英文原文。

打开官方英文原文 ↗

译文由机器翻译生成,仅供理解参考;有疑问请以官方英文原文为准。

中文点击中文段落可显示 / 隐藏英文原文本页译文覆盖 78%

14.19.1 聚合函数说明14.19.1 Aggregate Function Descriptions

本节介绍作用于值集合的聚合函数。它们通常与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 [over_clause], representing an optional 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))) FROM tbl_name;
SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM tbl_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]

    返回 expr 的平均值。可以使用 DISTINCT 选项来返回 expr 的不同值的平均值。Returns the average value of expr. The DISTINCT option can be used to return the average of the distinct values of expr.

    如果没有匹配的行,AVG() 返回 NULL。如果 expr 为 NULL,该函数也返回 NULL。If there are no matching rows, AVG() returns NULL. The function also returns NULL if expr is NULL.

    如果存在over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

    mysql> SELECT student_name, AVG(test_score)
           FROM student
           GROUP BY student_name;
    
  • BIT_AND(expr) [over_clause]

    返回expr中所有位的按位AND。Returns the bitwise AND of all bits in expr.

    结果类型取决于函数参数值是作为二进制字符串还是数字来计算: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, or NULL literal. 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, an ER_INVALID_BITWISE_OPERANDS_SIZE error occurs. If the argument size exceeds 511 bytes, an ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE error 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。在这种情况下,结果是一个与参数值长度相同的中性值。NULL values do not affect the result unless all values are NULL. 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 命令行客户端”。If BIT_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 if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

  • BIT_OR(expr) [over_clause]

    返回 expr 中所有位的按位 OR 结果。Returns the bitwise OR of all bits in expr.

    结果类型取决于函数参数值是作为二进制字符串还是数字来计算: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, or NULL literal. 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, an ER_INVALID_BITWISE_OPERANDS_SIZE error occurs. If the argument size exceeds 511 bytes, an ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE error 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。在这种情况下,结果是一个与参数值长度相同的中性值。NULL values do not affect the result unless all values are NULL. 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 命令行客户端”。If BIT_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 if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

  • BIT_XOR(expr) [over_clause]

    返回 expr 中所有位的按位 XOR。Returns the bitwise XOR of all bits in expr.

    结果类型取决于函数参数值是作为二进制字符串还是数字来计算: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, or NULL literal. 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, an ER_INVALID_BITWISE_OPERANDS_SIZE error occurs. If the argument size exceeds 511 bytes, an ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE error 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。在这种情况下,结果是一个与参数值长度相同的中性值。NULL values do not affect the result unless all values are NULL. 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 命令行客户端”。If BIT_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 if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

  • COUNT(expr) [over_clause]

    返回通过 SELECT 语句检索的行中 expr 的非 NULL 值的数量。结果是一个 BIGINT 值。Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.

    如果没有匹配的行,COUNT() 返回 0。COUNT(NULL) 返回 0。If there are no matching rows, COUNT() returns 0. COUNT(NULL) returns 0.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

    mysql> SELECT student.student_name,COUNT(*)
           FROM student,course
           WHERE student.student_id=course.student_id
           GROUP 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 contain NULL values.

    对于像 InnoDB 这样的事务存储引擎,存储精确的行数是有问题的。可能有多个事务同时进行,每个事务都可能影响计数。For transactional storage engines such as InnoDB, storing an exact row count is problematic. Multiple transactions may be occurring at the same time, each of which may affect the count.

    InnoDB does 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.InnoDB does 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(*) FROM tbl_name query performance for InnoDB tables is optimized for single-threaded workloads if there are no extra clauses such as WHERE or GROUP BY.

    InnoDB 处理 SELECT COUNT(*) 语句的方法是遍历最小的可用二级索引,除非索引或优化器提示指示优化器使用不同的索引。如果不存在二级索引,InnoDB 就通过扫描聚簇索引来处理 SELECT COUNT(*) 语句。InnoDB processes SELECT 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, InnoDB processes SELECT COUNT(*) statements by scanning the clustered index.

    如果索引记录未完全在缓冲池中,处理SELECT COUNT(*)语句需要一些时间。为了更快地计数,可以创建一个计数表,并让您的应用程序根据它执行的插入和删除来更新它。然而,在数千个并发事务同时对同一个计数表进行更新的情况下,这种方法可能无法很好地扩展。如果大约的行数就足够了,可以使用SHOW TABLE STATUS。Processing of SELECT 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, use SHOW TABLE STATUS.

    InnoDB 对 SELECT COUNT(*) 和 SELECT COUNT(1) 操作的处理方式相同。性能没有差异。InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference.

    对于 MyISAM 表,如果 COUNT(*) 用于从一个表中检索数据、未检索其他列且没有 WHERE 子句的 SELECT,则会被优化为非常快速地返回。例如:For MyISAM tables, COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is no WHERE clause. For example:

    mysql> SELECT COUNT(*) FROM student;
    

    该优化仅适用于 MyISAM 表,因为该存储引擎存储了精确的行数,可以非常快速地访问。COUNT(1) 只有在第一列定义为 NOT NULL 时,才适用相同的优化。This optimization only applies to MyISAM tables, 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 as NOT NULL.

  • COUNT(DISTINCT expr,[expr...])

    返回不同的非NULL expr 值的行数计数。Returns a count of the number of rows with different non-NULL expr values.

    如果没有匹配的行,COUNT(DISTINCT) 返回 0。If there are no matching rows, COUNT(DISTINCT) returns 0.

    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 contain NULL by giving a list of expressions. In standard SQL, you would have to do a concatenation of all expressions inside COUNT(DISTINCT ...).

  • GROUP_CONCAT(expr)

    此函数返回一个字符串结果,该结果是一个组中非NULL值的连接。如果没有非NULL值,则返回NULL。完整语法如下:This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. The full syntax is as follows:

    GROUP_CONCAT([DISTINCT] expr [,expr ...]
                 [ORDER BY {unsigned_integer | col_name | expr}
                     [ASC | DESC] [,col_name ...]]
                 [SEPARATOR str_val])
    
    mysql> SELECT student_name,
             GROUP_CONCAT(test_score)
           FROM student
           GROUP BY student_name;
    

    或者:Or:

    mysql> SELECT student_name,
             GROUP_CONCAT(DISTINCT test_score
                          ORDER BY test_score DESC SEPARATOR ' ')
           FROM student
           GROUP 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 the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (,). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

    结果被截断到由 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 the group_concat_max_len system 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 of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:

    SET [GLOBAL | SESSION] group_concat_max_len = val;
    
    Important

    在为 group_concat_max_len 设置值时,请考虑以下内容:When setting the value for group_concat_max_len, consider the following:

    • 估算 GROUP_CONCAT() 输出所需的最大长度,并相应地设置该值。Estimate the maximum length required for GROUP_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 is TEXT or BLOB unless group_concat_max_len is less than or equal to 512, in which case the result type is VARCHAR or VARBINARY.

    如果从 mysql 客户端内部调用 GROUP_CONCAT(),二进制字符串结果将根据 --binary-as-hex 的值以十六进制表示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。If GROUP_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 also CONCAT() and CONCAT_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 single JSON array 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. Returns NULL if the result contains no rows, or in the event of an error. If col_or_expr is NULL, the function returns an array of JSON [null] elements.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is 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. Returns NULL if the result contains no rows, or in the event of an error. An error occurs if any key name is NULL or the number of arguments is not equal to 2.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is 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 MySQL JSON data 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 a SELECT can 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 the ORDER BY specification 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 use GROUP BY (which usually imposes its own ordering regardless) and you prefer a particular key ordering, you can invoke JSON_OBJECTAGG() as a window function by including an OVER clause with an ORDER BY specification to impose a particular order on frame rows. The following examples show what happens with and without ORDER BY for a few different frame specifications.

    没有ORDER BY时,帧为整个分区:Without ORDER 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(在升序和降序中均适用):With ORDER BY, where the frame is the default of RANGE 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 并明确指定整个分区的帧:With ORDER BY and an explicit frame of the entire partition:

    mysql> SELECT JSON_OBJECTAGG(c, i)
           OVER (ORDER BY i
                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
            AS json_object
           FROM t;
    +-------------+
    | json_object |
    +-------------+
    | {"key": 5}  |
    | {"key": 5}  |
    | {"key": 5}  |
    +-------------+
    

    要返回特定的键值(例如最小值或最大值),请在相应的查询中包含 LIMIT 子句。例如:To return a particular key value (such as the smallest or largest), include a LIMIT clause 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 of expr. MAX() may take a string argument; in such cases, it returns the maximum string value. See Section 10.3.1, “How MySQL Uses Indexes”. The DISTINCT keyword can be used to find the maximum of the distinct values of expr, however, this produces the same result as omitting DISTINCT.

    如果没有匹配的行,或者 expr 为 NULL,MAX() 返回 NULL。If there are no matching rows, or if expr is NULL, MAX() returns NULL.

    如果存在over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

    mysql> SELECT student_name, MIN(test_score), MAX(test_score)
           FROM student
           GROUP BY student_name;
    

    对于 MAX(),MySQL 当前比较 ENUM 和 SET 列时,是按它们的字符串值进行比较,而不是按字符串在集合中的相对位置进行比较。这与 ORDER BY 比较它们的方式不同。For MAX(), MySQL currently compares ENUM and SET columns by their string value rather than by the string's relative position in the set. This differs from how ORDER BY compares them.

  • MIN([DISTINCT] expr) [over_clause]

    返回 expr 的最小值。MIN() 可以接受字符串参数;在这种情况下,它返回最小的字符串值。参见 第 10.3.1 节,“MySQL 如何使用索引”。DISTINCT 关键字可以用于查找 expr 不同值的最小值,但这与省略 DISTINCT 得到的结果相同。Returns the minimum value of expr. MIN() may take a string argument; in such cases, it returns the minimum string value. See Section 10.3.1, “How MySQL Uses Indexes”. The DISTINCT keyword can be used to find the minimum of the distinct values of expr, however, this produces the same result as omitting DISTINCT.

    如果没有匹配的行,或者 expr 为 NULL,MIN() 返回 NULL。If there are no matching rows, or if expr is NULL, MIN() returns NULL.

    如果存在over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

    mysql> SELECT student_name, MIN(test_score), MAX(test_score)
           FROM student
           GROUP BY student_name;
    

    对于 MIN(),MySQL 当前通过字符串值比较 ENUM 和 SET 列,而不是通过字符串在集合中的相对位置进行比较。这与 ORDER BY 对它们的比较方式不同。For MIN(), MySQL currently compares ENUM and SET columns by their string value rather than by the string's relative position in the set. This differs from how ORDER BY compares them.

  • STD(expr) [over_clause]

    返回 expr 的总体标准差。STD() 是标准 SQL 函数 STDDEV_POP() 的同义词,作为 MySQL 扩展提供。Returns the population standard deviation of expr. STD() is a synonym for the standard SQL function STDDEV_POP(), provided as a MySQL extension.

    如果没有匹配的行,或者 expr 为 NULL,STD() 返回 NULL。If there are no matching rows, or if expr is NULL, STD() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

  • STDDEV(expr) [over_clause]

    返回 expr 的总体标准差。STDDEV() 是标准 SQL 函数 STDDEV_POP() 的同义词,为了与 Oracle 兼容而提供。Returns the population standard deviation of expr. STDDEV() is a synonym for the standard SQL function STDDEV_POP(), provided for compatibility with Oracle.

    如果没有匹配的行,或者 expr 为 NULL,STDDEV() 将返回 NULL。If there are no matching rows, or if expr is NULL, STDDEV() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is 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 of expr (the square root of VAR_POP()). You can also use STD() or STDDEV(), which are equivalent but not standard SQL.

    如果没有匹配的行,或者 expr 为 NULL,STDDEV_POP() 将返回 NULL。If there are no matching rows, or if expr is NULL, STDDEV_POP() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is 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 of expr (the square root of VAR_SAMP().

    如果没有匹配的行,或者 expr 为 NULL,STDDEV_SAMP() 将返回 NULL。If there are no matching rows, or if expr is NULL, STDDEV_SAMP() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is 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 of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used to sum only the distinct values of expr.

    如果没有匹配的行,或者 expr 是 NULL,SUM() 将返回 NULL。If there are no matching rows, or if expr is NULL, SUM() returns NULL.

    如果存在over_clause,此函数将作为窗口函数执行。over_clause的说明见第 14.20.2 节,“窗口函数概念和语法”;它不能与DISTINCT一起使用。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

  • VAR_POP(expr) [over_clause]

    返回 expr 的总体标准方差。它将行视为整个总体,而不是样本,因此分母是行数。你也可以使用 VARIANCE(),它等价,但不是标准 SQL。Returns the population standard variance of expr. It considers rows as the whole population, not as a sample, so it has the number of rows as the denominator. You can also use VARIANCE(), which is equivalent but is not standard SQL.

    如果没有匹配的行,或者 expr 为 NULL,VAR_POP() 将返回 NULL。If there are no matching rows, or if expr is NULL, VAR_POP() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

  • VAR_SAMP(expr) [over_clause]

    返回 expr 的样本方差。也就是说,分母是行数减一。Returns the sample variance of expr. That is, the denominator is the number of rows minus one.

    如果没有匹配的行,或者 expr 为 NULL,VAR_SAMP() 将返回 NULL。If there are no matching rows, or if expr is NULL, VAR_SAMP() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.

  • VARIANCE(expr) [over_clause]

    返回expr的总体标准方差。VARIANCE()是标准 SQL 函数VAR_POP()的同义词,由 MySQL 扩展提供。Returns the population standard variance of expr. VARIANCE() is a synonym for the standard SQL function VAR_POP(), provided as a MySQL extension.

    如果没有匹配的行,或者expr为NULL,VARIANCE()将返回NULL。If there are no matching rows, or if expr is NULL, VARIANCE() returns NULL.

    如果存在over_clause,此函数作为窗口函数执行。over_clause 的描述见 第 14.20.2 节,“窗口函数的概念和语法”。This function executes as a window function if over_clause is present. over_clause is as described in Section 14.20.2, “Window Function Concepts and Syntax”.