8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

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

打开官方英文原文 ↗

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

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

14.15 信息函数14.15 Information Functions

表 14.20 信息函数Table 14.20 Information Functions

名称Name 说明Description
BENCHMARK() 重复执行一个表达式Repeatedly execute an expression
CHARSET() 返回参数的字符集Return the character set of the argument
COERCIBILITY() 返回字符串参数的排序规则强制值Return the collation coercibility value of the string argument
COLLATION() 返回字符串参数的排序规则Return the collation of the string argument
CONNECTION_ID() 返回连接的连接 ID(线程 ID)Return the connection ID (thread ID) for the connection
CURRENT_ROLE() 返回当前的活跃角色Return the current active roles
CURRENT_USER(), CURRENT_USER 经过身份验证的用户名和主机名The authenticated user name and host name
DATABASE() 返回默认(当前)数据库名称Return the default (current) database name
FOUND_ROWS() 对于带有 LIMIT 子句的 SELECT,如果没有 LIMIT 子句将返回的行数For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
ICU_VERSION() ICU 库版本ICU library version
LAST_INSERT_ID() 最后一次插入的 AUTOINCREMENT 列的值Value of the AUTOINCREMENT column for the last INSERT
ROLES_GRAPHML() 返回表示内存角色子图的 GraphML 文档Return a GraphML document representing memory role subgraphs
ROW_COUNT() 更新的行数The number of rows updated
SCHEMA() DATABASE() 的同义词Synonym for DATABASE()
SESSION_USER() USER() 的同义词Synonym for USER()
SYSTEM_USER() USER() 的同义词Synonym for USER()
USER() 客户端提供的用户名和主机名The user name and host name provided by the client
VERSION() 返回一个表示 MySQL 服务器版本的字符串Return a string that indicates the MySQL server version

  • BENCHMARK(count,expr)

    BENCHMARK() 函数会重复执行表达式 expr count 次。它可以用于测量 MySQL 处理该表达式的速度。返回值为 0,如果参数不合适(例如 NULL 或负数重复次数),则返回 NULL。The BENCHMARK() function executes the expression expr repeatedly count times. It may be used to time how quickly MySQL processes the expression. The result value is 0, or NULL for inappropriate arguments such as a NULL or negative repeat count.

    该函数的预期用法是在 mysql 客户端中使用,该客户端会报告查询执行时间:The intended use is from within the mysql client, which reports query execution times:

    mysql> SELECT BENCHMARK(1000000,AES_ENCRYPT('hello','goodbye'));
    +---------------------------------------------------+
    | BENCHMARK(1000000,AES_ENCRYPT('hello','goodbye')) |
    +---------------------------------------------------+
    |                                                 0 |
    +---------------------------------------------------+
    1 row in set (4.74 sec)
    

    报告的时间是客户端的经过时间,而不是服务器端的 CPU 时间。建议多次执行 BENCHMARK(),并根据服务器机器的负载情况来解释结果。The time reported is elapsed time on the client end, not CPU time on the server end. It is advisable to execute BENCHMARK() several times, and to interpret the result with regard to how heavily loaded the server machine is.

    BENCHMARK() 旨在测量标量表达式的运行性能,这对您使用它和解释结果的方式有一些重要影响:BENCHMARK() is intended for measuring the runtime performance of scalar expressions, which has some significant implications for the way that you use it and interpret the results:

    • 只能使用标量表达式。虽然表达式可以是子查询,但它必须返回单列且最多一行。例如,如果表 t 有多于一列或多于一行,则 BENCHMARK(10, (SELECT * FROM t)) 会失败。Only scalar expressions can be used. Although the expression can be a subquery, it must return a single column and at most a single row. For example, BENCHMARK(10, (SELECT * FROM t)) fails if the table t has more than one column or more than one row.

    • 执行一个SELECT expr语句N次数与执行SELECT BENCHMARK(N, expr)在所涉及的开销方面不同。两者的执行特征差异很大,你不应期望它们花费相同的时间。前者涉及解析器、优化器、表锁定和运行时评估N每次。后者仅涉及运行时评估N次数,而其他所有组件只执行一次。已分配的内存结构会被重复使用,并且运行时优化,例如对已评估的聚合函数结果进行本地缓存,可能会改变结果。使用BENCHMARK()因此通过为该组件赋予更多权重并去除“噪音”(由网络、解析器、优化器等引入)来衡量运行时组件的性能。Executing a SELECT expr statement N times differs from executing SELECT BENCHMARK(N, expr) in terms of the amount of overhead involved. The two have very different execution profiles and you should not expect them to take the same amount of time. The former involves the parser, optimizer, table locking, and runtime evaluation N times each. The latter involves only runtime evaluation N times, and all the other components just once. Memory structures already allocated are reused, and runtime optimizations such as local caching of results already evaluated for aggregate functions can alter the results. Use of BENCHMARK() thus measures performance of the runtime component by giving more weight to that component and removing the “noise” introduced by the network, parser, optimizer, and so forth.

  • CHARSET(str)

    返回字符串参数的字符集,如果参数为 NULL 则返回 NULL。Returns the character set of the string argument, or NULL if the argument is NULL.

    mysql> SELECT CHARSET('abc');
            -> 'utf8mb3'
    mysql> SELECT CHARSET(CONVERT('abc' USING latin1));
            -> 'latin1'
    mysql> SELECT CHARSET(USER());
            -> 'utf8mb3'
    
  • COERCIBILITY(str)

    返回字符串参数的排序规则强制值。Returns the collation coercibility value of the string argument.

    mysql> SELECT COERCIBILITY('abc' COLLATE utf8mb4_swedish_ci);
            -> 0
    mysql> SELECT COERCIBILITY(USER());
            -> 3
    mysql> SELECT COERCIBILITY('abc');
            -> 4
    mysql> SELECT COERCIBILITY(1000);
            -> 5
    

    返回值具有下表所示的含义。值越低,优先级越高。The return values have the meanings shown in the following table. Lower values have higher precedence.

    强制性Coercibility 意义Meaning 示例Example
    0 显式排序规则Explicit collation 带有 COLLATE 子句的值Value with COLLATE clause
    1 无排序规则No collation 不同排序规则的字符串连接Concatenation of strings with different collations
    2 隐式排序规则Implicit collation 列值、存储过程参数或局部变量Column value, stored routine parameter or local variable
    3 系统常量System constant USER() 返回值USER() return value
    4 可强制转换Coercible 字面字符串Literal string
    5 数字Numeric 数值或时间值Numeric or temporal value
    6 可忽略Ignorable NULL 或由 NULL 推导出的表达式NULL or an expression derived from NULL

    有关更多信息,请参见 第 12.8.4 节,“表达式中的排序规则强制性”。For more information, see Section 12.8.4, “Collation Coercibility in Expressions”.

  • COLLATION(str)

    返回字符串参数的排序规则。Returns the collation of the string argument.

    mysql> SELECT COLLATION('abc');
            -> 'utf8mb4_0900_ai_ci'
    mysql> SELECT COLLATION(_utf8mb4'abc');
            -> 'utf8mb4_0900_ai_ci'
    mysql> SELECT COLLATION(_latin1'abc');
            -> 'latin1_swedish_ci'
    
  • CONNECTION_ID()

    返回连接的连接 ID(线程 ID)。每个连接都有一个在当前连接客户端集合中唯一的 ID。Returns the connection ID (thread ID) for the connection. Every connection has an ID that is unique among the set of currently connected clients.

    CONNECTION_ID() 返回的值与信息模式 PROCESSLIST 表的 ID 列、Id 输出的 SHOW PROCESSLIST 列以及性能模式 threads 表的 PROCESSLIST_ID 列中显示的值类型相同。The value returned by CONNECTION_ID() is the same type of value as displayed in the ID column of the Information Schema PROCESSLIST table, the Id column of SHOW PROCESSLIST output, and the PROCESSLIST_ID column of the Performance Schema threads table.

    mysql> SELECT CONNECTION_ID();
            -> 23786
    
    Warning

    更改 pseudo_thread_id 系统变量的会话值会更改 CONNECTION_ID() 函数返回的值。Changing the session value of the pseudo_thread_id system variable changes the value returned by the CONNECTION_ID() function.

  • CURRENT_ROLE()

    返回一个 utf8mb3 字符串,包含当前会话的当前激活角色,用逗号分隔,如果没有,则返回 NONE。该值反映了 sql_quote_show_create 系统变量的设置。Returns a utf8mb3 string containing the current active roles for the current session, separated by commas, or NONE if there are none. The value reflects the setting of the sql_quote_show_create system variable.

    假设一个账户被授予的角色如下:Suppose that an account is granted roles as follows:

    GRANT 'r1', 'r2' TO 'u1'@'localhost';
    SET DEFAULT ROLE ALL TO 'u1'@'localhost';
    

    在 u1 的会话中,初始的 CURRENT_ROLE() 值指定默认帐户角色。使用 SET ROLE 可以更改该值:In sessions for u1, the initial CURRENT_ROLE() value names the default account roles. Using SET ROLE changes that:

    mysql> SELECT CURRENT_ROLE();
    +-------------------+
    | CURRENT_ROLE()    |
    +-------------------+
    | `r1`@`%`,`r2`@`%` |
    +-------------------+
    mysql> SET ROLE 'r1'; SELECT CURRENT_ROLE();
    +----------------+
    | CURRENT_ROLE() |
    +----------------+
    | `r1`@`%`       |
    +----------------+
    
  • CURRENT_USER, CURRENT_USER()

    返回服务器用于验证当前客户端的 MySQL 帐户的用户名和主机名组合。该帐户决定了您的访问权限。返回值是 utf8mb3 字符集的字符串。Returns the user name and host name combination for the MySQL account that the server used to authenticate the current client. This account determines your access privileges. The return value is a string in the utf8mb3 character set.

    CURRENT_USER() 的值可能与 USER() 的值不同。The value of CURRENT_USER() can differ from the value of USER().

    mysql> SELECT USER();
            -> 'davida@localhost'
    mysql> SELECT * FROM mysql.user;
    ERROR 1044: Access denied for user ''@'localhost' to
    database 'mysql'
    mysql> SELECT CURRENT_USER();
            -> '@localhost'
    

    该示例说明,尽管客户端指定的用户名为 davida(如 USER() 函数的值所示),服务器却使用匿名账户对客户端进行了认证(如 CURRENT_USER() 值中空的用户名部分所示)。这种情况可能发生的一个原因是权限表中没有列出 davida 的账户。The example illustrates that although the client specified a user name of davida (as indicated by the value of the USER() function), the server authenticated the client using an anonymous user account (as seen by the empty user name part of the CURRENT_USER() value). One way this might occur is that there is no account listed in the grant tables for davida.

    在存储程序或视图中,CURRENT_USER() 返回定义该对象的用户的账户(由其 DEFINER 值给出),除非使用 SQL SECURITY INVOKER 属性定义。在后一种情况下,CURRENT_USER() 返回对象的调用者。Within a stored program or view, CURRENT_USER() returns the account for the user who defined the object (as given by its DEFINER value) unless defined with the SQL SECURITY INVOKER characteristic. In the latter case, CURRENT_USER() returns the object's invoker.

    触发器和事件没有选项来定义 SQL SECURITY 特性,因此对于这些对象,CURRENT_USER() 返回定义该对象的用户帐户。要返回调用者,请使用 USER() 或 SESSION_USER()。Triggers and events have no option to define the SQL SECURITY characteristic, so for these objects, CURRENT_USER() returns the account for the user who defined the object. To return the invoker, use USER() or SESSION_USER().

    以下语句支持使用CURRENT_USER()函数来替代受影响用户或定义者的名称(以及可能的主机);在这种情况下,CURRENT_USER()会按需扩展:The following statements support use of the CURRENT_USER() function to take the place of the name of (and, possibly, a host for) an affected user or a definer; in such cases, CURRENT_USER() is expanded where and as needed:

    有关 CURRENT_USER() 扩展对复制的影响的信息,请参阅 第 19.5.1.8 节,“CURRENT_USER() 的复制”。For information about the implications that this expansion of CURRENT_USER() has for replication, see Section 19.5.1.8, “Replication of CURRENT_USER()”.

    此函数可用于 VARCHAR 或 TEXT 列的默认值,如下列 CREATE TABLE 语句所示:This function can be used for the default value of a VARCHAR or TEXT column, as shown in the following CREATE TABLE statement:

    CREATE TABLE t (c VARCHAR(288) DEFAULT (CURRENT_USER()));
    
  • DATABASE()

    以 utf8mb3 字符集返回默认(当前)数据库名称作为字符串。如果没有默认数据库,DATABASE() 返回 NULL。在存储例程中,默认数据库是与该例程关联的数据库,这不一定与调用上下文中的默认数据库相同。Returns the default (current) database name as a string in the utf8mb3 character set. If there is no default database, DATABASE() returns NULL. Within a stored routine, the default database is the database that the routine is associated with, which is not necessarily the same as the database that is the default in the calling context.

    mysql> SELECT DATABASE();
            -> 'test'
    

    如果没有默认数据库,DATABASE() 返回 NULL。If there is no default database, DATABASE() returns NULL.

  • FOUND_ROWS()

    Note

    SQL_CALC_FOUND_ROWS 查询修饰符及随附的 FOUND_ROWS() 函数已被弃用;预计将在未来版本的 MySQL 中移除。先使用 LIMIT 执行查询,然后执行第二条不带 LIMIT 的查询并使用 COUNT(*) 来确定是否有更多行。例如,不使用以下查询:The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS() function are deprecated; expect them to be removed in a future version of MySQL. Execute the query with LIMIT, and then a second query with COUNT(*) and without LIMIT to determine whether there are additional rows. For example, instead of these queries:

    SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name WHERE id > 100 LIMIT 10;
    SELECT FOUND_ROWS();
    

    请改用以下查询:Use these queries instead:

    SELECT * FROM tbl_name WHERE id > 100 LIMIT 10;
    SELECT COUNT(*) FROM tbl_name WHERE id > 100;
    

    COUNT(*) 可能会进行某些优化。SQL_CALC_FOUND_ROWS 会导致某些优化被禁用。COUNT(*) is subject to certain optimizations. SQL_CALC_FOUND_ROWS causes some optimizations to be disabled.

    SELECT 语句可以包含 LIMIT 子句,以限制服务器返回给客户端的行数。在某些情况下,希望了解如果没有 LIMIT 子句,语句本会返回多少行,但又不想再次运行该语句。要获得该行数,可以在 SELECT 语句中包含 SQL_CALC_FOUND_ROWS 选项,然后随后调用 FOUND_ROWS():A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include an SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:

    mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
        -> WHERE id > 100 LIMIT 10;
    mysql> SELECT FOUND_ROWS();
    

    第二个 SELECT 返回一个数字,表示如果第一个 SELECT 在没有 LIMIT 子句的情况下执行,本应返回多少行。The second SELECT returns a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause.

    在最近一次成功的 SELECT 语句中,如果没有使用 SQL_CALC_FOUND_ROWS 选项,FOUND_ROWS() 将返回该语句返回的结果集中的行数。如果语句包含 LIMIT 子句,FOUND_ROWS() 将返回达到限制的行数。例如,如果语句包含 FOUND_ROWS() 或 LIMIT 50, 10,LIMIT 10 分别返回 10 或 60。In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful SELECT statement, FOUND_ROWS() returns the number of rows in the result set returned by that statement. If the statement includes a LIMIT clause, FOUND_ROWS() returns the number of rows up to the limit. For example, FOUND_ROWS() returns 10 or 60, respectively, if the statement includes LIMIT 10 or LIMIT 50, 10.

    通过 FOUND_ROWS() 可获得的行数是临时的,并不打算在紧随 SELECT SQL_CALC_FOUND_ROWS 语句之后使用的语句中继续有效。如果您之后需要引用该值,请保存它:The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement. If you need to refer to the value later, save it:

    mysql> SELECT SQL_CALC_FOUND_ROWS * FROM ... ;
    mysql> SET @rows = FOUND_ROWS();
    

    如果您使用 SELECT SQL_CALC_FOUND_ROWS,MySQL 必须计算完整结果集中的行数。然而,这比在不使用 LIMIT 的情况下再次运行查询要快,因为结果集无需发送到客户端。If you are using SELECT SQL_CALC_FOUND_ROWS, MySQL must calculate how many rows are in the full result set. However, this is faster than running the query again without LIMIT, because the result set need not be sent to the client.

    SQL_CALC_FOUND_ROWS 和 FOUND_ROWS() 在你想要限制查询返回的行数,但又希望在不重新运行查询的情况下确定完整结果集的行数时非常有用。一个例子是呈现分页显示的网页脚本,其中包含指向显示搜索结果其他部分的页面的链接。使用 FOUND_ROWS() 可以让你确定剩余结果所需的其他页面数量。SQL_CALC_FOUND_ROWS and FOUND_ROWS() can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again. An example is a Web script that presents a paged display containing links to the pages that show other sections of a search result. Using FOUND_ROWS() enables you to determine how many other pages are needed for the rest of the result.

    在 UNION 语句中使用 SQL_CALC_FOUND_ROWS 和 FOUND_ROWS() 比在简单的 SELECT 语句中更复杂,因为 LIMIT 可能出现在 UNION 的多个位置。它可以应用于 UNION 中的单个 SELECT 语句,或者应用于整个 UNION 结果。The use of SQL_CALC_FOUND_ROWS and FOUND_ROWS() is more complex for UNION statements than for simple SELECT statements, because LIMIT may occur at multiple places in a UNION. It may be applied to individual SELECT statements in the UNION, or global to the UNION result as a whole.

    SQL_CALC_FOUND_ROWS 对 UNION 的意图是,它应返回在没有全局 LIMIT 的情况下会返回的行数。使用 SQL_CALC_FOUND_ROWS 与 UNION 的条件如下:The intent of SQL_CALC_FOUND_ROWS for UNION is that it should return the row count that would be returned without a global LIMIT. The conditions for use of SQL_CALC_FOUND_ROWS with UNION are:

    • SQL_CALC_FOUND_ROWS 关键字必须出现在 UNION 的第一个 SELECT 中。The SQL_CALC_FOUND_ROWS keyword must appear in the first SELECT of the UNION.

    • 只有在使用 UNION ALL 时,FOUND_ROWS() 的值才是精确的。如果使用没有 ALL 的 UNION,会进行重复值移除,并且 FOUND_ROWS() 的值只是近似值。The value of FOUND_ROWS() is exact only if UNION ALL is used. If UNION without ALL is used, duplicate removal occurs and the value of FOUND_ROWS() is only approximate.

    • 如果在 UNION 中没有 LIMIT,SQL_CALC_FOUND_ROWS 将被忽略,并返回为处理 UNION 创建的临时表中的行数。If no LIMIT is present in the UNION, SQL_CALC_FOUND_ROWS is ignored and returns the number of rows in the temporary table that is created to process the UNION.

    除了这里描述的情况之外,FOUND_ROWS() 的行为未定义(例如,在执行失败的 SELECT 语句之后)。Beyond the cases described here, the behavior of FOUND_ROWS() is undefined (for example, its value following a SELECT statement that fails with an error).

    Important

    FOUND_ROWS() 在基于语句的复制中无法可靠复制。此函数在基于行的复制中会自动复制。FOUND_ROWS() is not replicated reliably using statement-based replication. This function is automatically replicated using row-based replication.

  • ICU_VERSION()

    用于支持正则表达式操作的国际组件 Unicode (ICU) 库版本(参见 第 14.8.2 节,“正则表达式”)。此函数主要用于测试用例中。The version of the International Components for Unicode (ICU) library used to support regular expression operations (see Section 14.8.2, “Regular Expressions”). This function is primarily intended for use in test cases.

  • LAST_INSERT_ID(), LAST_INSERT_ID(expr)

    如果没有参数,LAST_INSERT_ID() 返回一个 BIGINT UNSIGNED(64 位)值,表示最近执行的 INSERT 语句成功插入 AUTO_INCREMENT 列的第一个自动生成的值。如果没有行被成功插入,LAST_INSERT_ID() 的值保持不变。With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.

    如果有参数,LAST_INSERT_ID() 返回一个无符号整数,如果参数为 NULL,则返回 NULL。With an argument, LAST_INSERT_ID() returns an unsigned integer, or NULL if the argument is NULL.

    例如,在插入一行生成 AUTO_INCREMENT 值之后,你可以这样获取该值:For example, after inserting a row that generates an AUTO_INCREMENT value, you can get the value like this:

    mysql> SELECT LAST_INSERT_ID();
            -> 195
    

    当前正在执行的语句不会影响 LAST_INSERT_ID() 的值。假设您使用一条语句生成了一个 AUTO_INCREMENT 值,然后在一条多行 INSERT 语句中引用 LAST_INSERT_ID(),该语句向具有自己 AUTO_INCREMENT 列的表插入行。第二条语句中 LAST_INSERT_ID() 的值保持不变;第二行及以后的行的值不受之前插入行的影响。(您应该注意,如果混合引用 LAST_INSERT_ID() 和 LAST_INSERT_ID(expr),其效果是未定义的。)The currently executing statement does not affect the value of LAST_INSERT_ID(). Suppose that you generate an AUTO_INCREMENT value with one statement, and then refer to LAST_INSERT_ID() in a multiple-row INSERT statement that inserts rows into a table with its own AUTO_INCREMENT column. The value of LAST_INSERT_ID() remains stable in the second statement; its value for the second and later rows is not affected by the earlier row insertions. (You should be aware that, if you mix references to LAST_INSERT_ID() and LAST_INSERT_ID(expr), the effect is undefined.)

    如果前一个语句返回错误,LAST_INSERT_ID() 的值是未定义的。对于事务表,如果由于错误语句被回滚,LAST_INSERT_ID() 的值将保持未定义。对于手动 ROLLBACK,LAST_INSERT_ID() 的值不会恢复到事务之前的状态;它将保持在 ROLLBACK 时的状态。If the previous statement returned an error, the value of LAST_INSERT_ID() is undefined. For transactional tables, if the statement is rolled back due to an error, the value of LAST_INSERT_ID() is left undefined. For manual ROLLBACK, the value of LAST_INSERT_ID() is not restored to that before the transaction; it remains as it was at the point of the ROLLBACK.

    在存储例程(存储过程或函数)或触发器的主体中,LAST_INSERT_ID() 的值的变化方式与在这些对象之外执行语句时相同。存储例程或触发器对随后语句所看到的 LAST_INSERT_ID() 值的影响取决于例程的类型:Within the body of a stored routine (procedure or function) or a trigger, the value of LAST_INSERT_ID() changes the same way as for statements executed outside the body of these kinds of objects. The effect of a stored routine or trigger upon the value of LAST_INSERT_ID() that is seen by following statements depends on the kind of routine:

    • 如果存储过程执行会改变 LAST_INSERT_ID() 值的语句,则在调用该过程后,随后的语句将看到被更改的值。If a stored procedure executes statements that change the value of LAST_INSERT_ID(), the changed value is seen by statements that follow the procedure call.

    • 对于会改变值的存储函数和触发器,当函数或触发器结束时,值会被恢复,因此其后的语句看不到已改变的值。For stored functions and triggers that change the value, the value is restored when the function or trigger ends, so statements coming after it do not see a changed value.

    生成的 ID 会在服务器上按每连接维持。这意味着函数返回给某个客户端的值是该客户端对某个AUTO_INCREMENT列AUTO_INCREMENT影响最近语句生成的第一个值。即使其他客户端对其他服务器生成了语句AUTO_INCREMENT自身的值。这种行为确保每个客户端都可以检索自己的 ID,而无需担心其他客户端的活动,也无需使用锁或事务。The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

    的值不会改变,如果您将一行的LAST_INSERT_ID()列设置为非AUTO_INCREMENT魔法“值(也就是说,一个既不是”也不是NULL的值)。0).The value of LAST_INSERT_ID() is not changed if you set the AUTO_INCREMENT column of a row to a non-“magic” value (that is, a value that is not NULL and not 0).

    Important

    如果使用单个INSERT语句插入多行,LAST_INSERT_ID()只返回为第一个插入的行生成的值。其原因是为了能够轻松地再现相同的INSERT,该值也不会受到影响。If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

    例如:For example:

    mysql> USE test;
    
    mysql> CREATE TABLE t (
           id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
           name VARCHAR(10) NOT NULL
           );
    
    mysql> INSERT INTO t VALUES (NULL, 'Bob');
    
    mysql> SELECT * FROM t;
    +----+------+
    | id | name |
    +----+------+
    |  1 | Bob  |
    +----+------+
    
    mysql> SELECT LAST_INSERT_ID();
    +------------------+
    | LAST_INSERT_ID() |
    +------------------+
    |                1 |
    +------------------+
    
    mysql> INSERT INTO t VALUES
           (NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa');
    
    mysql> SELECT * FROM t;
    +----+------+
    | id | name |
    +----+------+
    |  1 | Bob  |
    |  2 | Mary |
    |  3 | Jane |
    |  4 | Lisa |
    +----+------+
    
    mysql> SELECT LAST_INSERT_ID();
    +------------------+
    | LAST_INSERT_ID() |
    +------------------+
    |                2 |
    +------------------+
    

    虽然第二个 INSERT 语句向 t 插入了三行新记录,但为这些行中的第一行生成的 ID 是 2,并且在随后的 SELECT 语句中,LAST_INSERT_ID() 返回的就是这个值。Although the second INSERT statement inserted three new rows into t, the ID generated for the first of these rows was 2, and it is this value that is returned by LAST_INSERT_ID() for the following SELECT statement.

    如果你使用 INSERT IGNORE 并且该行被忽略,LAST_INSERT_ID() 将保持当前值不变(如果连接还没有成功执行过 INSERT,则返回 0),对于非事务表,AUTO_INCREMENT 计数器不会增加。对于 InnoDB 表,如果 innodb_autoinc_lock_mode 设置为 1 或 2,AUTO_INCREMENT 计数器将会增加,如下例所示:If you use INSERT IGNORE and the row is ignored, the LAST_INSERT_ID() remains unchanged from the current value (or 0 is returned if the connection has not yet performed a successful INSERT) and, for non-transactional tables, the AUTO_INCREMENT counter is not incremented. For InnoDB tables, the AUTO_INCREMENT counter is incremented if innodb_autoinc_lock_mode is set to 1 or 2, as demonstrated in the following example:

    mysql> USE test;
    
    mysql> SELECT @@innodb_autoinc_lock_mode;
    +----------------------------+
    | @@innodb_autoinc_lock_mode |
    +----------------------------+
    |                          1 |
    +----------------------------+
    
    mysql> CREATE TABLE `t` (
           `id` INT(11) NOT NULL AUTO_INCREMENT,
           `val` INT(11) DEFAULT NULL,
           PRIMARY KEY (`id`),
           UNIQUE KEY `i1` (`val`)
           ) ENGINE=InnoDB;
    
    # Insert two rows
    
    mysql> INSERT INTO t (val) VALUES (1),(2);
    
    # With auto_increment_offset=1, the inserted rows
    # result in an AUTO_INCREMENT value of 3
    
    mysql> SHOW CREATE TABLE t\G
    *************************** 1. row ***************************
           Table: t
    Create Table: CREATE TABLE `t` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `val` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `i1` (`val`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    
    # LAST_INSERT_ID() returns the first automatically generated
    # value that is successfully inserted for the AUTO_INCREMENT column
    
    mysql> SELECT LAST_INSERT_ID();
    +------------------+
    | LAST_INSERT_ID() |
    +------------------+
    |                1 |
    +------------------+
    
    # The attempted insertion of duplicate rows fail but errors are ignored
    
    mysql> INSERT IGNORE INTO t (val) VALUES (1),(2);
    Query OK, 0 rows affected (0.00 sec)
    Records: 2  Duplicates: 2  Warnings: 0
    
    # With innodb_autoinc_lock_mode=1, the AUTO_INCREMENT counter
    # is incremented for the ignored rows
    
    mysql> SHOW CREATE TABLE t\G
    *************************** 1. row ***************************
           Table: t
    Create Table: CREATE TABLE `t` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `val` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `i1` (`val`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    
    # The LAST_INSERT_ID is unchanged because the previous insert was unsuccessful
    
    mysql> SELECT LAST_INSERT_ID();
    +------------------+
    | LAST_INSERT_ID() |
    +------------------+
    |                1 |
    +------------------+
    

    有关更多信息,请参见 第 17.6.1.6 节,“InnoDB 中的 AUTO_INCREMENT 处理”。For more information, see Section 17.6.1.6, “AUTO_INCREMENT Handling in InnoDB”.

    如果 expr 作为参数传递给 LAST_INSERT_ID(),该函数将返回参数的值,并将其记为下一次 LAST_INSERT_ID() 将返回的值。这可以用于模拟序列:If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:

    1. 创建一个表来存储序列计数器并初始化它:Create a table to hold the sequence counter and initialize it:

      mysql> CREATE TABLE sequence (id INT NOT NULL);
      mysql> INSERT INTO sequence VALUES (0);
      
    2. 使用该表生成序列号,如下所示:Use the table to generate sequence numbers like this:

      mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
      mysql> SELECT LAST_INSERT_ID();
      

      UPDATE 语句会增加序列计数器,并导致下一次调用 LAST_INSERT_ID() 返回更新后的值。SELECT 语句检索该值。也可以使用 mysql_insert_id() C API 函数获取该值。参见 mysql_insert_id()。The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See mysql_insert_id().

    您可以在不调用 LAST_INSERT_ID() 的情况下生成序列,但以这种方式使用函数的好处在于该 ID 值会在服务器中保持为最后生成的自动值。它是多用户安全的,因为多个客户端可以执行 UPDATE 语句,并通过 SELECT 语句(或 mysql_insert_id())获取各自的序列值,而不会影响到其他生成自己序列值的客户端,也不会被其他客户端影响。You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

    请注意,mysql_insert_id() 仅在 INSERT 和 UPDATE 语句之后更新,因此在执行其他 SQL 语句如 SELECT 或 SET 后,不能使用 C API 函数来获取 LAST_INSERT_ID(expr) 的值。Note that mysql_insert_id() is only updated after INSERT and UPDATE statements, so you cannot use the C API function to retrieve the value for LAST_INSERT_ID(expr) after executing other SQL statements like SELECT or SET.

  • ROLES_GRAPHML()

    返回一个 utf8mb3 字符串,其中包含表示内存角色子图的 GraphML 文档。需要 ROLE_ADMIN 权限(或已弃用的 SUPER 权限)才能查看 <graphml> 元素中的内容。否则,结果只显示一个空元素:Returns a utf8mb3 string containing a GraphML document representing memory role subgraphs. The ROLE_ADMIN privilege (or the deprecated SUPER privilege) is required to see content in the <graphml> element. Otherwise, the result shows only an empty element:

    mysql> SELECT ROLES_GRAPHML();
    +---------------------------------------------------+
    | ROLES_GRAPHML()                                   |
    +---------------------------------------------------+
    | <?xml version="1.0" encoding="UTF-8"?><graphml /> |
    +---------------------------------------------------+
    
  • ROW_COUNT()

    ROW_COUNT() 返回值如下:ROW_COUNT() returns a value as follows:

    • DDL 语句:0。这适用于诸如 CREATE TABLE 或 DROP TABLE 之类的语句。DDL statements: 0. This applies to statements such as CREATE TABLE or DROP TABLE.

    • 除 SELECT 外的 DML 语句:受影响的行数。此适用于诸如 UPDATE、INSERT 或 DELETE(如前所述)的语句,但现在也适用于诸如 ALTER TABLE 和 LOAD DATA 的语句。DML statements other than SELECT: The number of affected rows. This applies to statements such as UPDATE, INSERT, or DELETE (as before), but now also to statements such as ALTER TABLE and LOAD DATA.

    • SELECT:如果语句返回结果集,则为 -1;如果没有,则为受影响的行数“。例如,对于”返回 -1。对于SELECT * FROM t1, ROW_COUNT()返回写入文件的行数。SELECT * FROM t1 INTO OUTFILE 'file_name', ROW_COUNT()在SELECT: -1 if the statement returns a result set, or the number of rows “affected” if it does not. For example, for SELECT * FROM t1, ROW_COUNT() returns -1. For SELECT * FROM t1 INTO OUTFILE 'file_name', ROW_COUNT() returns the number of rows written to the file.

    • SIGNAL 语句:0。SIGNAL statements: 0.

    表,如果没有任何可变长度列(UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE子句创建的表空间。For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.

    对于 REPLACE 语句,如果新行替换了旧行,则受影响的行数值为 2,因为在这种情况下,在删除重复行之后插入了一行新行。For REPLACE statements, the affected-rows value is 2 if the new row replaced an old row, because in this case, one row was inserted after the duplicate was deleted.

    对于 INSERT ... ON DUPLICATE KEY UPDATE 语句,如果行被插入为新行,每行的受影响行数值为 1;如果更新了现有行,则为 2;如果将现有行设置为其当前值,则为 0。如果指定了 CLIENT_FOUND_ROWS 标志,则当现有行被设置为其当前值时,受影响行数值为 1(而不是 0)。For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag, the affected-rows value is 1 (not 0) if an existing row is set to its current values.

    ROW_COUNT() 的值类似于 mysql_affected_rows() C API 函数的值,以及 mysql 客户端在执行语句后显示的行数。The ROW_COUNT() value is similar to the value from the mysql_affected_rows() C API function and the row count that the mysql client displays following statement execution.

    mysql> INSERT INTO t VALUES(1),(2),(3);
    Query OK, 3 rows affected (0.00 sec)
    Records: 3  Duplicates: 0  Warnings: 0
    
    mysql> SELECT ROW_COUNT();
    +-------------+
    | ROW_COUNT() |
    +-------------+
    |           3 |
    +-------------+
    1 row in set (0.00 sec)
    
    mysql> DELETE FROM t WHERE i IN(1,2);
    Query OK, 2 rows affected (0.00 sec)
    
    mysql> SELECT ROW_COUNT();
    +-------------+
    | ROW_COUNT() |
    +-------------+
    |           2 |
    +-------------+
    1 row in set (0.00 sec)
    
    Important

    ROW_COUNT() 在基于语句的复制中不能可靠地被复制。此函数在使用基于行的复制时会自动复制。ROW_COUNT() is not replicated reliably using statement-based replication. This function is automatically replicated using row-based replication.

  • SCHEMA()

    此函数是 DATABASE() 的同义词。This function is a synonym for DATABASE().

  • SESSION_USER()

    SESSION_USER() 是 USER() 的同义词。SESSION_USER() is a synonym for USER().

    与 USER() 类似,可以将此函数用作 VARCHAR 或 TEXT 列的默认值,如以下 CREATE TABLE 语句所示:Like USER(), this function can be used for the default value of a VARCHAR or TEXT column, as shown in the following CREATE TABLE statement:

    CREATE TABLE t (c VARCHAR(288) DEFAULT (SESSION_USER()));
    
  • SYSTEM_USER()

    SYSTEM_USER() 是 USER() 的同义词。SYSTEM_USER() is a synonym for USER().

    Note

    SYSTEM_USER() 函数与 SYSTEM_USER 权限不同。前者返回当前的 MySQL 帐号名称。后者区分系统用户和普通用户帐户类别(参见 第 8.2.11 节,“帐户类别”)。The SYSTEM_USER() function is distinct from the SYSTEM_USER privilege. The former returns the current MySQL account name. The latter distinguishes the system user and regular user account categories (see Section 8.2.11, “Account Categories”).

    与 USER() 类似,可以将此函数用作 VARCHAR 或 TEXT 列的默认值,如以下 CREATE TABLE 语句所示:Like USER(), this function can be used for the default value of a VARCHAR or TEXT column, as shown in the following CREATE TABLE statement:

    CREATE TABLE t (c VARCHAR(288) DEFAULT (SYSTEM_USER()));
    
  • USER()

    返回当前 MySQL 用户名和主机名,作为 utf8mb3 字符集的字符串。Returns the current MySQL user name and host name as a string in the utf8mb3 character set.

    mysql> SELECT USER();
            -> 'davida@localhost'
    

    该值表示您在连接到服务器时指定的用户名,以及您连接的客户端主机。该值可能与CURRENT_USER()的值不同。The value indicates the user name you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER().

    此函数可用于 VARCHAR 或 TEXT 列的默认值,如下列 CREATE TABLE 语句所示:This function can be used for the default value of a VARCHAR or TEXT column, as shown in the following CREATE TABLE statement:

    CREATE TABLE t (c VARCHAR(288) DEFAULT (USER()));
    
  • VERSION()

    返回一个字符串,该字符串表示 MySQL 服务器版本。该字符串使用utf8mb3字符集。该值除了版本号外,可能还有一个后缀。请参阅version系统变量的描述,见第 7.1.8 节,“服务器系统变量”。Returns a string that indicates the MySQL server version. The string uses the utf8mb3 character set. The value might have a suffix in addition to the version number. See the description of the version system variable in Section 7.1.8, “Server System Variables”.

    该函数在基于语句的复制中不安全。如果在 binlog_format 设置为 STATEMENT 时使用此函数,将记录一个警告。This function is unsafe for statement-based replication. A warning is logged if you use this function when binlog_format is set to STATEMENT.

    mysql> SELECT VERSION();
            -> '8.4.9-standard'