13.2.10.1 SELECT ... INTO Statement语句

The SELECT ... INTO form of SELECT enables a query result to be stored in variables or written to a file:SELECT语句的SELECT ... INTO形式可以将查询结果存储在变量中或写入文件中:

A given SELECT statement can contain at most one INTO clause, although as shown by the SELECT syntax description (see Section 13.2.10, “SELECT Statement”), the INTO can appear in different positions:给定的SELECT语句最多可以包含一个INTO子句,尽管如SELECT语法描述所示(参见第13.2.10节,“SELECT语句”),INTO可以出现在不同的位置:

The INTO position at the end of the statement is supported as of MySQL 8.0.20, and is the preferred position. MySQL 8.0.20支持语句末尾的INTO位置,这是首选位置。The position before a locking clause is deprecated as of MySQL 8.0.20; expect support for it to be removed in a future version of MySQL. 从MySQL8.0.20开始,锁定子句之前的位置已被弃用;在MySQL的未来版本中,对它的支持可能会被删除。In other words, INTO after FROM but not at the end of the SELECT produces a warning.换句话说,INTOFROM后面但不在SELECT的末尾会产生警告。

An INTO clause should not be used in a nested SELECT because such a SELECT must return its result to the outer context. 嵌套SELECT中不应使用INTO子句,因为这样的SELECT必须将其结果返回到外部上下文。There are also constraints on the use of INTO within UNION statements; see Section 13.2.10.3, “UNION Clause”.UNION语句中使用INTO也有限制;请参阅第13.2.10.3节,“UNION子句”

For the INTO var_list variant:对于INTO var_list变量:

INTO var_list can also be used with a TABLE statement, subject to these restrictions:INTO var_list也可以与TABLE语句一起使用,但有以下限制:

An example of such a statement is shown here:这种说法的一个例子如下:

TABLE employees ORDER BY lname DESC LIMIT 1
    INTO @id, @fname, @lname, @hired, @separated, @job_code, @store_id;

You can also select values from a VALUES statement that generates a single row into a set of user variables. 也可以从VALUES语句中选择值,该语句将单行生成一组用户变量。In this case, you must employ a table alias, and you must assign each value from the value list to a variable. 在这种情况下,必须使用表别名,并且必须将值列表中的每个值赋给一个变量。Each of the two statements shown here is equivalent to SET @x=2, @y=4, @z=8:这里显示的两个语句中的每一个都等同于SET @x=2, @y=4, @z=8

SELECT * FROM (VALUES ROW(2,4,8)) AS t INTO @x,@y,@z;

SELECT * FROM (VALUES ROW(2,4,8)) AS t(a,b,c) INTO @x,@y,@z;

User variable names are not case-sensitive. 用户变量名不区分大小写。See Section 9.4, “User-Defined Variables”.请参阅第9.4节,“用户定义变量”

The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. SELECT ... INTO OUTFILE 'file_name'形式将所选行写入文件。The file is created on the server host, so you must have the FILE privilege to use this syntax. 文件是在服务器主机上创建的,因此您必须具有FILE权限才能使用此语法。file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being modified. file_name不能是现有文件,这会阻止修改/etc/passwd和数据库表等文件。The character_set_filesystem system variable controls the interpretation of the file name.character_set_filesystem系统变量控制文件名的解释。

The SELECT ... INTO OUTFILE statement is intended to enable dumping a table to a text file on the server host. SELECT ... INTO OUTFILE语句用于将表转储到服务器主机上的文本文件中。To create the resulting file on some other host, SELECT ... INTO OUTFILE normally is unsuitable because there is no way to write a path to the file relative to the server host file system, unless the location of the file on the remote host can be accessed using a network-mapped path on the server host file system.要在其他主机上创建结果文件,SELECT ... INTO OUTFILE通常不合适,因为无法写入相对于服务器主机文件系统的文件路径,除非可以使用服务器主机文件系统上的网络映射路径访问远程主机上的文件位置。

Alternatively, if the MySQL client software is installed on the remote host, you can use a client command such as mysql -e "SELECT ..." > file_name to generate the file on that host.或者,如果MySQL客户端软件安装在远程主机上,则可以使用mysql -e "SELECT ..." > file_name以在该主机上生成文件。

SELECT ... INTO OUTFILE is the complement of LOAD DATA. SELECT ... INTO OUTFILELOAD DATA的补充。Column values are written converted to the character set specified in the CHARACTER SET clause. 列值被写入并转换为CHARACTER SET子句中指定的字符集。If no such clause is present, values are dumped using the binary character set. 如果不存在这样的子句,则使用binary字符集转储值。In effect, there is no character set conversion. 实际上,没有字符集转换。If a result set contains columns in several character sets, so is the output data file, and it may not be possible to reload the file correctly.如果结果集包含多个字符集中的列,则输出数据文件也是如此,并且可能无法正确重新加载文件。

The syntax for the export_options part of the statement consists of the same FIELDS and LINES clauses that are used with the LOAD DATA statement. 语句的export_options部分的语法由LOAD DATA语句使用的相同FIELDS子句和LINES子句组成。For information about the FIELDS and LINES clauses, including their default values and permissible values, see Section 13.2.7, “LOAD DATA Statement”.有关FIELDS子句和LINES子句的信息,包括其默认值和允许值,请参阅第13.2.7节,“加载数据语句”

FIELDS ESCAPED BY controls how to write special characters. FIELDS ESCAPED BY控制了如何写入特殊字符。If the FIELDS ESCAPED BY character is not empty, it is used when necessary to avoid ambiguity as a prefix that precedes following characters on output:如果FIELDS ESCAPED BY字符不为空,则在必要时将其用作前缀,以避免在输出时出现歧义,前缀位于以下字符之前:

The FIELDS TERMINATED BY, ENCLOSED BY, ESCAPED BY, or LINES TERMINATED BY characters must be escaped so that you can read the file back in reliably. 必须转义FIELDS TERMINATED BYENCLOSED BYESCAPED BYLINES TERMINATED BY字符,以便可靠地读回文件。ASCII NUL is escaped to make it easier to view with some pagers.ASCII-NUL被转义,以便于使用某些寻呼机查看。

The resulting file need not conform to SQL syntax, so nothing else need be escaped.生成的文件不需要符合SQL语法,因此不需要转义任何其他内容。

If the FIELDS ESCAPED BY character is empty, no characters are escaped and NULL is output as NULL, not \N. 如果按FIELDS ESCAPED BY字符为空,则不转义任何字符,并且NULL输出为NULL,而不是\NIt is probably not a good idea to specify an empty escape character, particularly if field values in your data contain any of the characters in the list just given.指定一个空转义字符可能不是一个好主意,特别是如果数据中的字段值包含刚刚给出的列表中的任何字符。

INTO OUTFILE can also be used with a TABLE statement when you want to dump all columns of a table into a text file. 当您要将表的所有列转储到文本文件中时,INTO-OUTFILE还可以与TABLE语句一起使用。In this case, the ordering and number of rows can be controlled using ORDER BY and LIMIT; these clauses must precede INTO OUTFILE. 在这种情况下,可以使用ORDER BYLIMIT控制行的顺序和数量;这些子句必须在INTO OUTFILE之前。TABLE ... INTO OUTFILE supports the same export_options as does SELECT ... INTO OUTFILE, and it is subject to the same restrictions on writing to the file system. ABLE ... INTO OUTFILE支持与SELECT ... INTO OUTFILE相同的export_options,并且它在写入文件系统时受到相同的限制。An example of such a statement is shown here:这种说法的一个例子如下:

TABLE employees ORDER BY lname LIMIT 1000
    INTO OUTFILE '/tmp/employee_data_1.txt'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"', ESCAPED BY '\'
    LINES TERMINATED BY '\n';

You can also use SELECT ... INTO OUTFILE with a VALUES statement to write values directly into a file. 您也可以使用SELECT ... INTO OUTFILE配合VALUES语句将值直接写入文件。An example is shown here:示例如下:

SELECT * FROM (VALUES ROW(1,2,3),ROW(4,5,6),ROW(7,8,9)) AS t
    INTO OUTFILE '/tmp/select-values.txt';

You must use a table alias; column aliases are also supported, and can optionally be used to write values only from desired columns. 必须使用表别名;还支持列别名,并且可以选择仅从所需列写入值。You can also use any or all of the export options supported by SELECT ... INTO OUTFILE to format the output to the file.您还可以使用SELECT ... INTO OUTFILE支持的任何或所有导出选项将输出格式化为文件。

Here is an example that produces a file in the comma-separated values (CSV) format used by many programs:下面是一个以逗号分隔值(CSV)格式生成文件的示例,许多程序都使用该格式:

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;

If you use INTO DUMPFILE instead of INTO OUTFILE, MySQL writes only one row into the file, without any column or line termination and without performing any escape processing. 如果使用INTO DUMPFILE而不是INTO OUTFILE,MySQL只向文件中写入一行,没有任何列或行终止,也没有执行任何转义处理。This is useful for selecting a BLOB value and storing it in a file.这对于选择BLOB值并将其存储在文件中非常有用。

TABLE also supports INTO DUMPFILE. TABLE还支持INTO DUMPFILEIf the table contains more than one row, you must also use LIMIT 1 to limit the output to a single row. 如果表包含多行,则还必须使用LIMIT 1将输出限制为一行。INTO DUMPFILE can also be used with SELECT * FROM (VALUES ROW()[, ...]) AS table_alias [LIMIT 1]. INTO DUMPFILE还可以与SELECT * FROM (VALUES ROW()[, ...]) AS table_alias [LIMIT 1]配合使用。See Section 13.2.14, “VALUES Statement”.请参阅第13.2.14节,“VALUES语句”

Note注意

Any file created by INTO OUTFILE or INTO DUMPFILE is owned by the operating system user under whose account mysqld runs. INTO OUTFILEINTO DUMPFILE创建的任何文件都归运行mysqld的操作系统用户所有。(You should never run mysqld as root for this and other reasons.) (由于这个原因和其他原因,您不应该以root身份运行mysqld。)As of MySQL 8.0.17, the umask for file creation is 0640; you must have sufficient access privileges to manipulate the file contents. 从MySQL8.0.17开始,文件创建的单元掩码是0640;您必须具有足够的访问权限才能操作文件内容。Prior to MySQL 8.0.17, the umask is 0666 and the file is writable by all users on the server host.在MySQL 8.0.17之前,umask是0666,该文件可由服务器主机上的所有用户写入。

If the secure_file_priv system variable is set to a nonempty directory name, the file to be written must be located in that directory.如果secure_file_priv系统变量设置为非空目录名,则要写入的文件必须位于该目录中。

In the context of SELECT ... INTO statements that occur as part of events executed by the Event Scheduler, diagnostics messages (not only errors, but also warnings) are written to the error log, and, on Windows, to the application event log. 在作为事件调度器执行的事件的一部分发生的SELECT ... INTO语句的上下文中,诊断消息(不仅是错误,还有警告)会写入错误日志,在Windows上还会写入应用程序事件日志。For additional information, see Section 25.4.5, “Event Scheduler Status”.有关更多信息,请参阅第25.4.5节,“事件调度器状态”

As of MySQL 8.0.22, support is provided for periodic synchronization of output files written to by SELECT INTO OUTFILE and SELECT INTO DUMPFILE, enabled by setting the select_into_disk_sync server system variable introduced in that version. 从MySQL 8.0.22开始,支持定期同步SELECT INTO OUTFILESELECT INTO DUMPFILE写入的输出文件,通过设置该版本中引入的select_into_disk_sync服务器系统变量启用。Output buffer size and optional delay can be set using, respectively, select_into_buffer_size and select_into_disk_sync_delay. 输出缓冲区大小和可选延迟可以分别使用以下选项进行设置:select_into_buffer_sizeselect_into_disk_sync_delayFor more information, see the descriptions of these system variables.有关详细信息,请参阅这些系统变量的说明。