8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

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

打开官方英文原文 ↗

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

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

15.2.9 LOAD DATA 语句15.2.9 LOAD DATA Statement

LOAD DATA
    [LOW_PRIORITY | CONCURRENT] [LOCAL]
    INFILE 'file_name'
    [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [CHARACTER SET charset_name]
    [{FIELDS | COLUMNS}
        [TERMINATED BY 'string']
        [[OPTIONALLY] ENCLOSED BY 'char']
        [ESCAPED BY 'char']
    ]
    [LINES
        [STARTING BY 'string']
        [TERMINATED BY 'string']
    ]
    [IGNORE number {LINES | ROWS}]
    [(col_name_or_user_var
        [, col_name_or_user_var] ...)]
    [SET col_name={expr | DEFAULT}
        [, col_name={expr | DEFAULT}] ...]

LOAD DATA 语句以极高速度将文本文件中的行读入表。文件可以从服务器主机或客户端主机读取,具体取决于是否给出了 LOCAL 修饰符。LOCAL 也影响数据解释和错误处理。The LOAD DATA statement reads rows from a text file into a table at a very high speed. The file can be read from the server host or the client host, depending on whether the LOCAL modifier is given. LOCAL also affects data interpretation and error handling.

LOAD DATA 是 SELECT ... INTO OUTFILE“。(参见 第 15.2.13.1 节,”SELECT ...INTO 语句“。)要将数据从表写入文件,使用 SELECT ... INTO OUTFILE。要将文件读回表,使用 LOAD DATA。FIELDS 和 LINES 子句的语法在两个语句中相同。LOAD DATA is the complement of SELECT ... INTO OUTFILE. (See Section 15.2.13.1, “SELECT ... INTO Statement”.) To write data from a table to a file, use SELECT ... INTO OUTFILE. To read the file back into a table, use LOAD DATA. The syntax of the FIELDS and LINES clauses is the same for both statements.

mysqlimport 工具提供了另一种加载数据文件的方法;它通过向服务器发送 LOAD DATA 语句来操作。参见 第 6.5.5 节,“mysqlimport — 一个数据导入程序”。The mysqlimport utility provides another way to load data files; it operates by sending a LOAD DATA statement to the server. See Section 6.5.5, “mysqlimport — A Data Import Program”.

有关 INSERT 与 LOAD DATA 的效率以及加快 LOAD DATA 的方法,请参见 第 10.2.5.1 节,“优化 INSERT 语句”。For information about the efficiency of INSERT versus LOAD DATA and speeding up LOAD DATA, see Section 10.2.5.1, “Optimizing INSERT Statements”.

非 LOCAL 与 LOCAL 操作Non-LOCAL Versus LOCAL Operation

LOCAL 修饰符会影响这些 LOAD DATA 的方面,与非 LOCAL 操作相比:The LOCAL modifier affects these aspects of LOAD DATA, compared to non-LOCAL operation:

LOCAL 仅在服务器和客户端都已配置允许时有效。例如,如果 mysqld 是在禁用 local_infile 系统变量的情况下启动的,则 LOCAL 会产生错误。参见 第 8.1.6 节 “LOAD DATA LOCAL 的安全性考虑”。LOCAL works only if the server and your client both have been configured to permit it. For example, if mysqld was started with the local_infile system variable disabled, LOCAL produces an error. See Section 8.1.6, “Security Considerations for LOAD DATA LOCAL”.

输入文件字符集Input File Character Set

文件名必须以字面字符串形式给出。在 Windows 上,路径名中的反斜杠应指定为正斜杠或双反斜杠。服务器使用 character_set_filesystem 系统变量指定的字符集来解释文件名。The file name must be given as a literal string. On Windows, specify backslashes in path names as forward slashes or doubled backslashes. The server interprets the file name using the character set indicated by the character_set_filesystem system variable.

默认情况下,服务器使用由character_set_database系统变量指示的字符集来解释文件内容。如果文件内容使用的字符集不同于此默认值,最好使用CHARACTER SET子句指定该字符集。字符集binary表示“不进行转换。”By default, the server interprets the file contents using the character set indicated by the character_set_database system variable. If the file contents use a character set different from this default, it is a good idea to specify that character set by using the CHARACTER SET clause. A character set of binary specifies “no conversion.”

SET NAMES 和 character_set_client 的设置不会影响文件内容的解释。SET NAMES and the setting of character_set_client do not affect interpretation of file contents.

LOAD DATA 将文件中的所有字段解释为相同的字符集,无论字段值加载到哪列的数据类型。为了正确解释文件,必须确保它使用正确的字符集写入。例如,如果你写一个数据文件,mysqldump -T,或者通过发送 SELECT ... INTO OUTFILE 语句 mysql,务必使用 --default-character-set option,将文件加载时使用的输出写入 LOAD DATA“。LOAD DATA interprets all fields in the file as having the same character set, regardless of the data types of the columns into which field values are loaded. For proper interpretation of the file, you must ensure that it was written with the correct character set. For example, if you write a data file with mysqldump -T or by issuing a SELECT ... INTO OUTFILE statement in mysql, be sure to use a --default-character-set option to write output in the character set to be used when the file is loaded with LOAD DATA.

Note

无法加载使用 ucs2、utf16、utf16le,或 utf32 字符集的数据文件。It is not possible to load data files that use the ucs2, utf16, utf16le, or utf32 character set.

Input File Location 这些Input File Location

规则决定了 LOAD DATA 输入文件位置:These rules determine the LOAD DATA input file location:

  • 如果 LOCAL,文件必须位于服务器主机上。服务器直接读取文件,具体定位如下:If LOCAL is not specified, the file must be located on the server host. The server reads the file directly, locating it as follows:

    • 如果文件名是绝对路径名,服务器按规定使用。If the file name is an absolute path name, the server uses it as given.

    • 如果文件名是带有前导组件的相对路径名,服务器会查找相对于其数据目录的文件。If the file name is a relative path name with leading components, the server looks for the file relative to its data directory.

    • 如果文件名没有前导组件,服务器会在默认数据库的数据库目录中查找该文件。If the file name has no leading components, the server looks for the file in the database directory of the default database.

  • 如果指定LOCAL,文件必须位于客户端主机上。客户端程序读取该文件,定位方式如下:If LOCAL is specified, the file must be located on the client host. The client program reads the file, locating it as follows:

    • 如果文件名是绝对路径名,客户端程序按给定使用它。If the file name is an absolute path name, the client program uses it as given.

    • 如果文件名是相对路径名,客户端程序会查找相对于其调用目录的文件。If the file name is a relative path name, the client program looks for the file relative to its invocation directory.

    当使用 LOCAL 时,客户端程序读取文件并将其内容发送给服务器。服务器在其存储临时文件的目录中创建文件副本。参见 节 B.3.3.5,“MySQL 存储临时文件的地方”。该目录中复制空间不足可能导致 LOAD DATA LOCAL句失败。When LOCAL is used, the client program reads the file and sends its contents to the server. The server creates a copy of the file in the directory where it stores temporary files. See Section B.3.3.5, “Where MySQL Stores Temporary Files”. Lack of sufficient space for the copy in this directory can cause the LOAD DATA LOCAL statement to fail.

非LOCAL规则意味着服务器会从其数据目录中读取名为./myfile.txt的文件,而名为myfile.txt的文件则会从默认数据库的数据库目录中读取。例如,如果在默认数据库为db1时执行以下LOAD DATA语句,服务器会从db1的数据库目录中读取文件data.txt,即使该语句明确地将文件加载到db2数据库中的表:The non-LOCAL rules mean that the server reads a file named as ./myfile.txt relative to its data directory, whereas it reads a file named as myfile.txt from the database directory of the default database. For example, if the following LOAD DATA statement is executed while db1 is the default database, the server reads the file data.txt from the database directory for db1, even though the statement explicitly loads the file into a table in the db2 database:

LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
Note

服务器还使用非LOCAL规则来定位IMPORT TABLE语句的.sdi文件。The server also uses the non-LOCAL rules to locate .sdi files for the IMPORT TABLE statement.

安全要求Security Requirements

对于非LOCAL加载操作,服务器会读取位于服务器主机上的文本文件,因此必须满足以下安全要求:For a non-LOCAL load operation, the server reads a text file located on the server host, so these security requirements must be satisfied:

对于LOCAL加载操作,客户端程序会读取位于客户端主机上的文本文件。因为文件内容是由客户端通过连接发送到服务器的,所以使用LOCAL比服务器直接访问文件稍慢。另一方面,您不需要FILE权限,并且文件可以位于客户端程序可访问的任何目录中。For a LOCAL load operation, the client program reads a text file located on the client host. Because the file contents are sent over the connection by the client to the server, using LOCAL is a bit slower than when the server accesses the file directly. On the other hand, you do not need the FILE privilege, and the file can be located in any directory the client program can access.

重复键和错误处理Duplicate-Key and Error Handling

REPLACE和IGNORE修饰符控制对在唯一键值(PRIMARY KEY或UNIQUE索引值)上重复现有表行的新(输入)行的处理方式:The REPLACE and IGNORE modifiers control handling of new (input) rows that duplicate existing table rows on unique key values (PRIMARY KEY or UNIQUE index values):

LOCAL修饰符的效果与IGNORE相同。这是因为服务器无法在操作过程中阻止文件传输。The LOCAL modifier has the same effect as IGNORE. This occurs because the server has no way to stop transmission of the file in the middle of the operation.

如果没有指定 REPLACE、IGNORE 或 LOCAL,则当发现重复键值时会出错,其余文本文件被忽略。If none of REPLACE, IGNORE, or LOCAL is specified, an error occurs when a duplicate key value is found, and the rest of the text file is ignored.

除了影响前述的重复密钥处理外,IGNORE 和 LOCAL也会影响错误处理:In addition to affecting duplicate-key handling as just described, IGNORE and LOCAL also affect error handling:

  • 当既未指定 IGNORE指定 LOCAL,则数据解释错误终止操作。When neither IGNORE nor LOCAL is specified, data-interpretation errors terminate the operation.

  • 当指定 IGNORE——或 LOCAL(不含 REPLACE——时,数据解释错误会变成警告,加载操作继续,即使 SQL 模式受限。示例请参见 Column Value Assign。When IGNORE—or LOCAL without REPLACE—is specified, data interpretation errors become warnings and the load operation continues, even if the SQL mode is restrictive. For examples, see Column Value Assignment.

索引处理Index Handling

在加载操作中忽略外键约束,执行 SET foreign_key_checks = 0 语句后再执行 LOAD DATA“。To ignore foreign key constraints during the load operation, execute a SET foreign_key_checks = 0 statement before executing LOAD DATA.

如果你在空的 LOAD DATA“,所有非唯一索引都会单独创建(如 REPAIR TABLE)。通常这样会让 LOAD DATA“在有多个索引时更快。在极端情况下,你可以更快地创建索引,方法是关闭索引 ALTER TABLE ... DISABLE KEYS在将文件加载到表格并重新创建索引前,先禁用密钥,并重新创建索引,格式为 ALTER TABLE ... ENABLE KEYS加载文件后启用密钥。参见 第 10.2.5.1 节,“优化 INSERT 语句”。If you use LOAD DATA on an empty MyISAM table, all nonunique indexes are created in a separate batch (as for REPAIR TABLE). Normally, this makes LOAD DATA much faster when you have many indexes. In some extreme cases, you can create the indexes even faster by turning them off with ALTER TABLE ... DISABLE KEYS before loading the file into the table and re-creating the indexes with ALTER TABLE ... ENABLE KEYS after loading the file. See Section 10.2.5.1, “Optimizing INSERT Statements”.

字段和行处理Field and Line Handling

对于LOAD DATA 和 SELECT ... INTO OUTFILE 语句中,FIELDS 和 LINES 子句的语法相同。这两个子句都是可选的,但如果两者都指定,FIELDS必须在 LINESFor both the LOAD DATA and SELECT ... INTO OUTFILE statements, the syntax of the FIELDS and LINES clauses is the same. Both clauses are optional, but FIELDS must precede LINES if both are specified.

如果你指定一个FIELDS子句,其每个子子句(TERMINATED BY,[OPTIONALLY] ENCLOSED BY,以及ESCAPED BY)也是可选的,但你必须至少指定其中一个。这些子句的参数只能包含 ASCII 字符。If you specify a FIELDS clause, each of its subclauses (TERMINATED BY, [OPTIONALLY] ENCLOSED BY, and ESCAPED BY) is also optional, except that you must specify at least one of them. Arguments to these clauses are permitted to contain only ASCII characters.

如果你不指定 FIELDS 或 LINES 子句,默认设置与你写下此文相同:If you specify no FIELDS or LINES clause, the defaults are the same as if you had written this:

FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED BY '\n' STARTING BY ''

反斜杠是 SQL 语句中字符串的 MySQL 转义字符。因此,要指定一个字面上的反斜杠,你必须指定两个反斜杠才能让该值被解释为单个反斜杠。转义序列 '\t' 和 '\n' 分别表示制表符和换行符。Backslash is the MySQL escape character within strings in SQL statements. Thus, to specify a literal backslash, you must specify two backslashes for the value to be interpreted as a single backslash. The escape sequences '\t' and '\n' specify tab and newline characters, respectively.

换句话说,默认设置使 LOAD DATA 在读取输入时的行为如下:In other words, the defaults cause LOAD DATA to act as follows when reading input:

  • 在换行符处查找行边界。Look for line boundaries at newlines.

  • 不要跳过任何行前缀。Do not skip any line prefix.

  • 在制表符处将行拆分为字段。Break lines into fields at tabs.

  • 不期望字段被任何引号字符括起来。Do not expect fields to be enclosed within any quoting characters.

  • 将转义字符 \ 前的字符解释为转义序列。例如,\t、\n 和 \\ 分别表示制表符、换行符和反斜杠。有关完整的转义序列列表,请参阅后面关于 FIELDS ESCAPED BY 的讨论。Interpret characters preceded by the escape character \ as escape sequences. For example, \t, \n, and \\ signify tab, newline, and backslash, respectively. See the discussion of FIELDS ESCAPED BY later for the full list of escape sequences.

相反,默认设置使 SELECT ... INTO OUTFILE 在写入输出时的行为如下:Conversely, the defaults cause SELECT ... INTO OUTFILE to act as follows when writing output:

  • 在字段之间写入制表符。Write tabs between fields.

  • 不要将字段括在任何引号字符中。Do not enclose fields within any quoting characters.

  • 在字段值中出现的制表符、换行符或 \ 使用 \ 进行转义。Use \ to escape instances of tab, newline, or \ that occur within field values.

  • 在行尾写入换行符。Write newlines at the ends of lines.

Note

对于在 Windows 系统上生成的文本文件,正确读取文件可能需要使用 LINES TERMINATED BY '\r\n',因为 Windows 程序通常使用两个字符作为行终止符。一些程序,例如 WordPad,在写入文件时可能使用 \r 作为行终止符。要读取这样的文件,请使用 LINES TERMINATED BY '\r'。For a text file generated on a Windows system, proper file reading might require LINES TERMINATED BY '\r\n' because Windows programs typically use two characters as a line terminator. Some programs, such as WordPad, might use \r as a line terminator when writing files. To read such files, use LINES TERMINATED BY '\r'.

如果所有输入行都有一个你想忽略的共同前缀,可以使用 LINES STARTING BY 'prefix_string' 来跳过该前缀 及其之前的内容。如果某一行不包含该前缀,则整行会被跳过。假设你发出如下语句:If all the input lines have a common prefix that you want to ignore, you can use LINES STARTING BY 'prefix_string' to skip the prefix and anything before it. If a line does not include the prefix, the entire line is skipped. Suppose that you issue the following statement:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test
  FIELDS TERMINATED BY ','  LINES STARTING BY 'xxx';

如果数据文件如下所示:If the data file looks like this:

xxx"abc",1
something xxx"def",2
"ghi",3

生成的行是 ("abc",1) 和 ("def",2)。文件中的第三行被跳过,因为它不包含该前缀。The resulting rows are ("abc",1) and ("def",2). The third row in the file is skipped because it does not contain the prefix.

IGNORE number LINES 子句可用于忽略文件开头的行。例如,可以使用 IGNORE 1 LINES 来跳过包含列名的初始标题行:The IGNORE number LINES clause can be used to ignore lines at the start of the file. For example, you can use IGNORE 1 LINES to skip an initial header line containing column names:

LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;

当你将 SELECT ... INTO OUTFILE 与 LOAD DATA 一起使用,将数据库中的数据写入文件,然后稍后再将文件读取回数据库时,两条语句的字段和行处理选项必须匹配。否则,LOAD DATA 无法正确解释文件内容。假设你使用 SELECT ... INTO OUTFILE 编写一个以逗号分隔字段的文件:When you use SELECT ... INTO OUTFILE in tandem with LOAD DATA to write data from a database into a file and then read the file back into the database later, the field- and line-handling options for both statements must match. Otherwise, LOAD DATA does not interpret the contents of the file properly. Suppose that you use SELECT ... INTO OUTFILE to write a file with fields delimited by commas:

SELECT * INTO OUTFILE 'data.txt'
  FIELDS TERMINATED BY ','
  FROM table2;

读取该逗号分隔文件的正确语句是:To read the comma-delimited file, the correct statement is:

LOAD DATA INFILE 'data.txt' INTO TABLE table2
  FIELDS TERMINATED BY ',';

如果你尝试使用下面显示的语句读取文件,它就不会工作,因为它指示 LOAD DATA 查找字段之间的制表符:If instead you tried to read the file with the statement shown following, it would not work because it instructs LOAD DATA to look for tabs between fields:

LOAD DATA INFILE 'data.txt' INTO TABLE table2
  FIELDS TERMINATED BY '\t';

可能的结果是每条输入行将被解释为单个字段。The likely result is that each input line would be interpreted as a single field.

LOAD DATA 可以用来读取从外部来源获取的文件。例如,许多程序可以以逗号分隔值(CSV)格式导出数据,这样每行的字段用逗号分隔并用双引号括起来,且首行是列名。如果此类文件中的行由回车/换行对终止,下述语句演示了加载该文件时使用的字段和行处理选项:LOAD DATA can be used to read files obtained from external sources. For example, many programs can export data in comma-separated values (CSV) format, such that lines have fields separated by commas and enclosed within double quotation marks, with an initial line of column names. If the lines in such a file are terminated by carriage return/newline pairs, the statement shown here illustrates the field- and line-handling options you would use to load the file:

LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;

如果输入值不一定用引号括起来,在 ENCLOSED BY 选项前使用 OPTIONALLY。If the input values are not necessarily enclosed within quotation marks, use OPTIONALLY before the ENCLOSED BY option.

任何字段或行处理选项都可以指定为空字符串('')。如果不为空,FIELDS [OPTIONALLY] ENCLOSED BY 和 FIELDS ESCAPED BY 的值必须是单个字符。FIELDS TERMINATED BY、LINES STARTING BY 和 LINES TERMINATED BY 的值可以超过一个字符。例如,要编写以回车/换行对终止的行,或读取包含此类行的文件,请指定 LINES TERMINATED BY '\r\n' 子句。Any of the field- or line-handling options can specify an empty string (''). If not empty, the FIELDS [OPTIONALLY] ENCLOSED BY and FIELDS ESCAPED BY values must be a single character. The FIELDS TERMINATED BY, LINES STARTING BY, and LINES TERMINATED BY values can be more than one character. For example, to write lines that are terminated by carriage return/linefeed pairs, or to read a file containing such lines, specify a LINES TERMINATED BY '\r\n' clause.

要读取包含由 %% 行分隔的笑话的文件,你可以这样做To read a file containing jokes that are separated by lines consisting of %%, you can do this

CREATE TABLE jokes
  (a INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  joke TEXT NOT NULL);
LOAD DATA INFILE '/tmp/jokes.txt' INTO TABLE jokes
  FIELDS TERMINATED BY ''
  LINES TERMINATED BY '\n%%\n' (joke);

FIELDS [OPTIONALLY] ENCLOSED BY 控制字段的引用。对于输出(SELECT ... INTO OUTFILE),如果省略 OPTIONALLY,所有字段都会被 ENCLOSED BY 字符括起来。如下所示是使用逗号作为字段分隔符的输出示例:FIELDS [OPTIONALLY] ENCLOSED BY controls quoting of fields. For output (SELECT ... INTO OUTFILE), if you omit the word OPTIONALLY, all fields are enclosed by the ENCLOSED BY character. An example of such output (using a comma as the field delimiter) is shown here:

"1","a string","100.20"
"2","a string containing a , comma","102.20"
"3","a string containing a \" quote","102.20"
"4","a string containing a \", quote and comma","102.20"

如果你指定 OPTIONALLYENCLOSED BY 字符仅用于包含字符串数据类型的列的值(例如 CHAR, BINARY,TEXT或 ENUM):If you specify OPTIONALLY, the ENCLOSED BY character is used only to enclose values from columns that have a string data type (such as CHAR, BINARY, TEXT, or ENUM):

1,"a string",100.20
2,"a string containing a , comma",102.20
3,"a string containing a \" quote",102.20
4,"a string containing a \", quote and comma",102.20

字段值中出现 ENCLOSED BY 字符时,通过在字段值前加 ESCAPED BY 字符来避免。此外,如果你指定空的 ESCAPED BY 值,可能会无意中生成无法被正确读取的输出 LOAD DATA。例如,如果转义字符为空,刚才显示的输出会显示如下。注意第四行第二个字段后面有一个逗号,这个逗号(错误地)似乎终止了该字段:Occurrences of the ENCLOSED BY character within a field value are escaped by prefixing them with the ESCAPED BY character. Also, if you specify an empty ESCAPED BY value, it is possible to inadvertently generate output that cannot be read properly by LOAD DATA. For example, the preceding output just shown would appear as follows if the escape character is empty. Observe that the second field in the fourth line contains a comma following the quote, which (erroneously) appears to terminate the field:

1,"a string",100.20
2,"a string containing a , comma",102.20
3,"a string containing a " quote",102.20
4,"a string containing a ", quote and comma",102.20

对于输入,ENCLOSED BY 字符(如果存在)会从字段值的末端被移除。(无论是否指定 OPTIONALLY;OPTIONALLY 不影响输入解释。)ENCLOSED BY 字符前的出现,前置 ESCAPED BY 字符,则被视为当前字段值的一部分。For input, the ENCLOSED BY character, if present, is stripped from the ends of field values. (This is true regardless of whether OPTIONALLY is specified; OPTIONALLY has no effect on input interpretation.) Occurrences of the ENCLOSED BY character preceded by the ESCAPED BY character are interpreted as part of the current field value.

如果字段以 ENCLOSED BY,则该字符的实例仅在后面跟随字段或行 TERMINATED BY。为避免歧义,字段值中出现 ENCLOSED BY 字符的出现可以加倍,并被解释为该字符的单一实例。例如,如果指定了ENCLOSED BY '"',引号的处理方式如下:If the field begins with the ENCLOSED BY character, instances of that character are recognized as terminating a field value only if followed by the field or line TERMINATED BY sequence. To avoid ambiguity, occurrences of the ENCLOSED BY character within a field value can be doubled and are interpreted as a single instance of the character. For example, if ENCLOSED BY '"' is specified, quotation marks are handled as shown here:

"The ""BIG"" boss"  -> The "BIG" boss
The "BIG" boss      -> The "BIG" boss
The ""BIG"" boss    -> The ""BIG"" boss

FIELDS ESCAPED BY 控制如何读写特殊字符:FIELDS ESCAPED BY controls how to read or write special characters:

  • 输入时,如果FIELDS ESCAPED BY 不是空的,则该字符的出现会被剥离,接下来的字符作为字段值的一部分被字面取用。一些两个字符的序列是例外,其中第一个字符是转义字符。这些序列在下表中展示(转义字符使用\)。NULL将在本节后面详细说明。For input, if the FIELDS ESCAPED BY character is not empty, occurrences of that character are stripped and the following character is taken literally as part of a field value. Some two-character sequences that are exceptions, where the first character is the escape character. These sequences are shown in the following table (using \ for the escape character). The rules for NULL handling are described later in this section.

    Character 转义序列Escape Sequence
    \0 一个 ASCII NUL (X'00') 字符An ASCII NUL (X'00') character
    \b 一个退格字符A backspace character
    \n 换行符(换行)字符A newline (linefeed) character
    \r 回车字符A carriage return character
    \t 制表符。A tab character.
    \Z ASCII 26(控制 Z)ASCII 26 (Control+Z)
    \N NULL

    关于 \-escape 语法的更多信息,请参见 第 11.1.1 节,“字符串文字”。For more information about \-escape syntax, see Section 11.1.1, “String Literals”.

    如果 FIELDS ESCAPED BY 为空,则不会发生转义序列解释。If the FIELDS ESCAPED BY character is empty, escape-sequence interpretation does not occur.

  • 对于输出,如果FIELDS ESCAPED BY字符不为空,它将用于在输出中前缀以下字符:For output, if the FIELDS ESCAPED BY character is not empty, it is used to prefix the following characters on output:

    • The FIELDS ESCAPED BY 字符。The FIELDS ESCAPED BY character.

    • FIELDS [OPTIONALLY] ENCLOSED BY。The FIELDS [OPTIONALLY] ENCLOSED BY character.

    • FIELDS TERMINATED BY 和 LINES TERMINATED BY,如果 ENCLOSED BY 字符为空或未指定。The first character of the FIELDS TERMINATED BY and LINES TERMINATED BY values, if the ENCLOSED BY character is empty or unspecified.

    • ASCII 0(实际在转义字符后写的是 ASCII 0,而非零值字节)。ASCII 0 (what is actually written following the escape character is ASCII 0, not a zero-valued byte).

    如果FIELDS ESCAPED BY 为空,则无字符转义,NULL输出为 NULL而非 \N。指定空转义字符可能不是好主意,尤其是当数据中的字段值包含上述列表中的任何字符时。If the FIELDS ESCAPED BY character is empty, no characters are escaped and NULL is output as NULL, not \N. It 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.

在某些情况下,字段处理和行处理选项会相互作用:In certain cases, field- and line-handling options interact:

  • 如果 LINES TERMINATED BY 是空字符串,且 FIELDS TERMINATED BY 非空,则行的结尾也以 FIELDS TERMINATED BY结束。If LINES TERMINATED BY is an empty string and FIELDS TERMINATED BY is nonempty, lines are also terminated with FIELDS TERMINATED BY.

  • 如果FIELDS TERMINATED BY以及FIELDS ENCLOSED BY values are both empty (''), a fixed-row (nondelimited) format is used. With fixed-row format, no delimiters are used between fields (but you can still have a line terminator). Instead, column values are read and written using a field width wide enough to hold all values in the field. For TINYINT, SMALLINT, MEDIUMINT, INT,以及BIGINT, the field widths are 4, 6, 8, 11, and 20, respectively, no matter what the declared display width is.If the FIELDS TERMINATED BY and FIELDS ENCLOSED BY values are both empty (''), a fixed-row (nondelimited) format is used. With fixed-row format, no delimiters are used between fields (but you can still have a line terminator). Instead, column values are read and written using a field width wide enough to hold all values in the field. For TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT, the field widths are 4, 6, 8, 11, and 20, respectively, no matter what the declared display width is.

    LINES TERMINATED BY 仍用于分隔行。如果一行不包含所有字段,其余列将被设置为默认值。如果没有行终止符,应将其设置为 ''。此时,文本文件必须包含每一行的所有字段。LINES TERMINATED BY is still used to separate lines. If a line does not contain all fields, the rest of the columns are set to their default values. If you do not have a line terminator, you should set this to ''. In this case, the text file must contain all fields for each row.

    固定行格式还会影响后文所述的 NULL 值的处理。Fixed-row format also affects handling of NULL values, as described later.

    Note

    如果你使用多字节字符集,固定大小格式是不起作用的。Fixed-size format does not work if you are using a multibyte character set.

NULL 值的处理取决于 FIELDS 和 LINES 选项:Handling of NULL values varies according to the FIELDS and LINES options in use:

  • 对于默认的 FIELDS 和 LINES 值,NULL 作为输出字段值写为 \N,输入字段 \N 读取为 NULL(假设 ESCAPED BY 字符为 \)。For the default FIELDS and LINES values, NULL is written as a field value of \N for output, and a field value of \N is read as NULL for input (assuming that the ESCAPED BY character is \).

  • 如果 FIELDS ENCLOSED BY 不是空的,包含字面词 NULL会被读取为 NULL 值。这与 NULL,后者被读取为字符串 'NULL'。If FIELDS ENCLOSED BY is not empty, a field containing the literal word NULL as its value is read as a NULL value. This differs from the word NULL enclosed within FIELDS ENCLOSED BY characters, which is read as the string 'NULL'.

  • 如果 FIELDS ESCAPED BY 为空,则 NULL 表示为 NULLIf FIELDS ESCAPED BY is empty, NULL is written as the word NULL.

  • 采用固定行格式(当 FIELDS TERMINATED BY 和 FIELDS ENCLOSED BY 均为空时使用),NULL 被写成空字符串。这使得表中的 NULL 值和空字符串在写入文件时无法区分,因为两者都是空字符串。如果你需要在读取文件时区分这两者,不应使用固定行格式。With fixed-row format (which is used when FIELDS TERMINATED BY and FIELDS ENCLOSED BY are both empty), NULL is written as an empty string. This causes both NULL values and empty strings in the table to be indistinguishable when written to the file because both are written as empty strings. If you need to be able to tell the two apart when reading the file back in, you should not use fixed-row format.

尝试将 NULL 加载到 NOT NULL 列时,会根据 Column Value Assignment 中描述的规则,产生警告或错误。An attempt to load NULL into a NOT NULL column produces either a warning or an error according to the rules described in Column Value Assignment.

某些情况不支持LOAD DATASome cases are not supported by LOAD DATA:

  • Fixed-size 行(FIELDS TERMINATED BY 和 FIELDS ENCLOSED BY 均为空)以及 BLOB 或 TEXT 列。Fixed-size rows (FIELDS TERMINATED BY and FIELDS ENCLOSED BY both empty) and BLOB or TEXT columns.

  • 如果你指定一个分隔符与另一个分隔符相同或前缀,LOAD DATA无法正确解释输入。例如,以下 FIELDS 子句会引发问题:If you specify one separator that is the same as or a prefix of another, LOAD DATA cannot interpret the input properly. For example, the following FIELDS clause would cause problems:

    FIELDS TERMINATED BY '"' ENCLOSED BY '"'
    
  • 如果 FIELDS ESCAPED BY 为空,则包含 FIELDS ENCLOSED BY 或 LINES TERMINATED BY跟 FIELDS TERMINATED BY 会导致 LOAD DATA“会提前停止读取字段或行。这是因为 LOAD DATA 无法正确确定字段或行值的结束位置。If FIELDS ESCAPED BY is empty, a field value that contains an occurrence of FIELDS ENCLOSED BY or LINES TERMINATED BY followed by the FIELDS TERMINATED BY value causes LOAD DATA to stop reading a field or line too early. This happens because LOAD DATA cannot properly determine where the field or line value ends.

Column List 规范Column List Specification

以下示例加载了 persondata:The following example loads all columns of the persondata table:

LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata;

默认情况下,如果在 LOAD DATA 语句末尾未提供列列表,则输入行应包含每个表列的字段。如果您只想加载表的一些列,请指定列列表:By default, when no column list is provided at the end of the LOAD DATA statement, input lines are expected to contain a field for each table column. If you want to load only some of a table's columns, specify a column list:

LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata
(col_name_or_user_var [, col_name_or_user_var] ...);

如果输入文件中的字段顺序与表中的列顺序不一致,也必须指定列列表。否则,MySQL 无法判断如何将输入字段与表列匹配。You must also specify a column list if the order of the fields in the input file differs from the order of the columns in the table. Otherwise, MySQL cannot tell how to match input fields with table columns.

输入预处理Input Preprocessing

LOAD DATA 语法中的每个 col_name_or_user_var 实例可以是列名或用户变量。使用用户变量时,SET 子句允许您在将结果分配给列之前对其值进行预处理转换。Each instance of col_name_or_user_var in LOAD DATA syntax is either a column name or a user variable. With user variables, the SET clause enables you to perform preprocessing transformations on their values before assigning the result to columns.

SET 子句中的用户变量可以以多种方式使用。以下示例直接使用第一个输入列作为 t1.column1 的值,并将第二个输入列分配给一个用户变量,在用于 t1.column2 的值之前对其进行除法运算:User variables in the SET clause can be used in several ways. The following example uses the first input column directly for the value of t1.column1, and assigns the second input column to a user variable that is subjected to a division operation before being used for the value of t1.column2:

LOAD DATA INFILE 'file.txt'
  INTO TABLE t1
  (column1, @var1)
  SET column2 = @var1/100;

SET 子句可用于提供不从输入文件派生的值。以下语句将 column3 设置为当前日期和时间:The SET clause can be used to supply values not derived from the input file. The following statement sets column3 to the current date and time:

LOAD DATA INFILE 'file.txt'
  INTO TABLE t1
  (column1, column2)
  SET column3 = CURRENT_TIMESTAMP;

您还可以通过将输入值分配给用户变量并不将该变量分配给任何表列来丢弃输入值:You can also discard an input value by assigning it to a user variable and not assigning the variable to any table column:

LOAD DATA INFILE 'file.txt'
  INTO TABLE t1
  (column1, @dummy, column2, @dummy, column3);

列/变量列表和 SET 子句的使用受以下限制:Use of the column/variable list and SET clause is subject to the following restrictions:

  • SET 子句中的赋值运算符左侧应仅有列名。Assignments in the SET clause should have only column names on the left hand side of assignment operators.

  • 可以在 SET 赋值的右侧使用子查询。返回用于分配给列的值的子查询只能是标量子查询。此外,不能使用子查询从正在加载的表中选择数据。You can use subqueries in the right hand side of SET assignments. A subquery that returns a value to be assigned to a column may be a scalar subquery only. Also, you cannot use a subquery to select from the table that is being loaded.

  • IGNORE number LINES 子句忽略的行不会被列/变量列表或 SET 子句处理。Lines ignored by an IGNORE number LINES clause are not processed for the column/variable list or SET clause.

  • 由于用户变量没有显示宽度,固定行格式加载数据时不能使用用户变量。User variables cannot be used when loading data with fixed-row format because user variables do not have a display width.

列值分配Column Value Assignment

为了处理输入行,LOAD DATA 将其拆分为字段,并根据存在的列/变量列表和 SET 子句使用字段值。然后,将生成的行插入到表中。如果表有 BEFORE INSERT 或 AFTER INSERT 触发器,它们将在插入行之前或之后被激活。To process an input line, LOAD DATA splits it into fields and uses the values according to the column/variable list and the SET clause, if they are present. Then the resulting row is inserted into the table. If there are BEFORE INSERT or AFTER INSERT triggers for the table, they are activated before or after inserting the row, respectively.

字段值的解释和向表列的赋值取决于以下因素:Interpretation of field values and assignment to table columns depends on these factors:

  • SQL 模式(sql_mode 系统变量的值)。该模式可以是非限制性的,也可以以各种方式限制。例如,可以启用严格 SQL 模式,或者模式可以包含如 NO_ZERO_DATE 或 NO_ZERO_IN_DATE 的值。The SQL mode (the value of the sql_mode system variable). The mode can be nonrestrictive, or restrictive in various ways. For example, strict SQL mode can be enabled, or the mode can include values such as NO_ZERO_DATE or NO_ZERO_IN_DATE.

  • IGNORE 和 LOCAL 修饰符的存在或缺失。Presence or absence of the IGNORE and LOCAL modifiers.

这些因素结合在一起,会通过 LOAD DATA 产生限制性或非限制性的数据解释:Those factors combine to produce restrictive or nonrestrictive data interpretation by LOAD DATA:

  • 如果 SQL 模式是限制性的,并且未指定 IGNORE 或 LOCAL 修饰符,则数据解释为限制性。错误会终止加载操作。Data interpretation is restrictive if the SQL mode is restrictive and neither the IGNORE nor the LOCAL modifier is specified. Errors terminate the load operation.

  • 如果 SQL 模式是非限制性的,或者指定了 IGNORE 或 LOCAL 修饰符,则数据解释为非限制性。(特别是,如果指定任一修饰符,当 REPLACE 修饰符被省略时,它会 覆盖 限制性 SQL 模式。)错误会变为警告,加载操作继续进行。Data interpretation is nonrestrictive if the SQL mode is nonrestrictive or the IGNORE or LOCAL modifier is specified. (In particular, either modifier if specified overrides a restrictive SQL mode when the REPLACE modifier is omitted.) Errors become warnings and the load operation continues.

限制性数据解释使用以下规则:Restrictive data interpretation uses these rules:

  • 字段过多或过少会产生错误。Too many or too few fields results an error.

  • 将 NULL(也就是 \N)赋值给非 NULL 列会产生错误。Assigning NULL (that is, \N) to a non-NULL column results in an error.

  • 超出列数据类型范围的值会产生错误。A value that is out of range for the column data type results in an error.

  • 无效值会产生错误。例如,数值列中出现 'x' 值会产生错误,而不是转换为 0。Invalid values produce errors. For example, a value such as 'x' for a numeric column results in an error, not conversion to 0.

相比之下,非限制性数据解释使用以下规则:By contrast, nonrestrictive data interpretation uses these rules:

  • 如果输入行字段过多,多余的字段会被忽略,并统计警告次数增加。If an input line has too many fields, the extra fields are ignored and the number of warnings is incremented.

  • 如果输入行字段不足,会为缺失输入字段的列分配默认值。默认值分配见 第 13.6 节,“数据类型默认值”。If an input line has too few fields, the columns for which input fields are missing are assigned their default values. Default value assignment is described in Section 13.6, “Data Type Default Values”.

  • 将 NULL(也就是 \N)赋值给非 NULL 列,会分配该列数据类型的隐式默认值。隐式默认值见 第 13.6 节,“数据类型默认值”。Assigning NULL (that is, \N) to a non-NULL column results in assignment of the implicit default value for the column data type. Implicit default values are described in Section 13.6, “Data Type Default Values”.

  • 无效值会产生警告而不是错误,并转换为该列数据类型的“最接近” 有效值。例如:Invalid values produce warnings rather than errors, and are converted to the “closest” valid value for the column data type. Examples:

    • 数值列中出现 'x' 值会被转换为 0。A value such as 'x' for a numeric column results in conversion to 0.

    • 超出范围的数值或时间值会被裁剪到该列数据类型范围的最接近端点。An out-of-range numeric or temporal value is clipped to the closest endpoint of the range for the column data type.

    • An invalid value for a DATETIME, DATE,或TIME column is inserted as the implicit default value, regardless of the SQL mode NO_ZERO_DATE setting. The implicit default is the appropriate “零” value for the type ('0000-00-00 00:00:00', '0000-00-00',或'00:00:00'). See Section 13.2, “Date and Time Data Types”.An invalid value for a DATETIME, DATE, or TIME column is inserted as the implicit default value, regardless of the SQL mode NO_ZERO_DATE setting. The implicit default is the appropriate “zero” value for the type ('0000-00-00 00:00:00', '0000-00-00', or '00:00:00'). See Section 13.2, “Date and Time Data Types”.

  • LOAD DATA 对空字段值的解释与缺失字段不同:LOAD DATA interprets an empty field value differently from a missing field:

    • 对于字符串类型,列设置为空字符串。For string types, the column is set to the empty string.

    • 对于数字类型,列设置为 0。For numeric types, the column is set to 0.

    • 对于日期和时间类型,列被设置为该类型的相应 “zero” 值。参见 第 13.2 节,“日期和时间数据类型”。For date and time types, the column is set to the appropriate “zero” value for the type. See Section 13.2, “Date and Time Data Types”.

    这些值与在 INSERT 或 UPDATE语句时得到的值相同。These are the same values that result if you assign an empty string explicitly to a string, numeric, or date or time type explicitly in an INSERT or UPDATE statement.

TIMESTAMP 列仅在该列存在 NULL 值(即 \N)且列未声明允许 NULL 值,或者如果 TIMESTAMP 列默认值为当前时间戳,字段TIMESTAMP columns are set to the current date and time only if there is a NULL value for the column (that is, \N) and the column is not declared to permit NULL values, or if the TIMESTAMP column default value is the current timestamp and it is omitted from the field list when a field list is specified.

LOAD DATA 将所有输入视为字符串,因此不能用数字表示 ENUM 或 SET 列,就像 INSERT 语句。所有 ENUM 和 SET 值必须以字符串形式指定。LOAD DATA regards all input as strings, so you cannot use numeric values for ENUM or SET columns the way you can with INSERT statements. All ENUM and SET values must be specified as strings.

BIT 值不能直接用二进制符号加载(例如,b'011010')。为了解决这个问题,可以使用 SET 子句,去除开头的 b' 和后面的 '并进行 base-2 到 base-10 的转换,使 MySQL 正确地将这些值加载到 BIT 列:BIT values cannot be loaded directly using binary notation (for example, b'011010'). To work around this, use the SET clause to strip off the leading b' and trailing ' and perform a base-2 to base-10 conversion so that MySQL loads the values into the BIT column properly:

$> cat /tmp/bit_test.txt
b'10'
b'1111111'
$> mysql test
mysql> LOAD DATA INFILE '/tmp/bit_test.txt'
       INTO TABLE bit_test (@var1)
       SET b = CAST(CONV(MID(@var1, 3, LENGTH(@var1)-3), 2, 10) AS UNSIGNED);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Deleted: 0  Skipped: 0  Warnings: 0

mysql> SELECT BIN(b+0) FROM bit_test;
+----------+
| BIN(b+0) |
+----------+
| 10       |
| 1111111  |
+----------+
2 rows in set (0.00 sec)

对于 BIT 值 0b 二进制符号(例如,0b011010使用 SET 子句,去除前导的 0b:For BIT values in 0b binary notation (for example, 0b011010), use this SET clause instead to strip off the leading 0b:

SET b = CAST(CONV(MID(@var1, 3, LENGTH(@var1)-2), 2, 10) AS UNSIGNED)

分区表支持Partitioned Table Support

LOAD DATA使用显式分区选择,使用 PARTITION 子句,并列出一个或多个以逗号分隔的分区、子分区或两者。使用该子句时,如果文件中的任何行无法插入列表中指定的任何分区或子分区,则该语句将失败,错误为 发现一行不匹配给定的分区集。更多信息和示例请参见 第 26.5 节,“分区选择”。LOAD DATA supports explicit partition selection using the PARTITION clause with a list of one or more comma-separated names of partitions, subpartitions, or both. When this clause is used, if any rows from the file cannot be inserted into any of the partitions or subpartitions named in the list, the statement fails with the error Found a row not matching the given partition set. For more information and examples, see Section 26.5, “Partition Selection”.

并发考虑Concurrency Considerations

LOW_PRIORITY修饰符,LOAD DATA 语句的执行会延迟到没有其他客户端读取该表。这只影响仅使用表级锁定的存储引擎(例如 MyISAMMEMORYMERGEWith the LOW_PRIORITY modifier, execution of the LOAD DATA statement is delayed until no other clients are reading from the table. This affects only storage engines that use only table-level locking (such as MyISAM, MEMORY, and MERGE).

使用CONCURRENT 修饰符和满足并发插入条件的 MyISAM 表(即中间无空块),其他线程可以在 LOAD DATA。该修饰符影响 LOAD DATA一点点,即使没有其他线程同时使用该表。With the CONCURRENT modifier and a MyISAM table that satisfies the condition for concurrent inserts (that is, it contains no free blocks in the middle), other threads can retrieve data from the table while LOAD DATA is executing. This modifier affects the performance of LOAD DATA a bit, even if no other thread is using the table at the same time.

语句结果信息Statement Result Information

当 LOAD DATA statement 结束时,返回以下格式的信息字符串:When the LOAD DATA statement finishes, it returns an information string in the following format:

Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

与使用 INSERT 语句(参见 第 15.2.7 节,“INSERT 语句”),但 LOAD DATA也会在输入行字段过少或过多时触发警告。Warnings occur under the same circumstances as when values are inserted using the INSERT statement (see Section 15.2.7, “INSERT Statement”), except that LOAD DATA also generates warnings when there are too few or too many fields in the input row.

你可以使用 SHOW WARNINGS来获取第一个 max_error_count 警告的列表,作为问题所在的信息。参见 第 15.7.7.42 节,”SHOW WARNINGS Statement“。You can use SHOW WARNINGS to get a list of the first max_error_count warnings as information about what went wrong. See Section 15.7.7.42, “SHOW WARNINGS Statement”.

如果您正在使用 C API,可以通过调用 mysql_info() 函数获取有关语句的信息。请参阅 mysql_info()。If you are using the C API, you can get information about the statement by calling the mysql_info() function. See mysql_info().

复制注意事项Replication Considerations

LOAD DATA 被认为在基于语句的复制中是不安全的。如果您在使用 LOAD DATA 时设置了 binlog_format=STATEMENT,每个要应用更改的复制服务器都会创建一个包含数据的临时文件。即使源服务器启用了二进制日志加密,该临时文件也不会被加密。如果需要加密,请改用基于行的或混合的二进制日志格式,这样复制服务器就不会创建临时文件。有关 LOAD DATA 与复制之间交互的更多信息,请参见 第 19.5.1.19 节,“复制与 LOAD DATA”。LOAD DATA is considered unsafe for statement-based replication. If you use LOAD DATA with binlog_format=STATEMENT, each replica on which the changes are to be applied creates a temporary file containing the data. This temporary file is not encrypted, even if binary log encryption is active on the source, If encryption is required, use row-based or mixed binary logging format instead, for which replicas do not create the temporary file. For more information on the interaction between LOAD DATA and replication, see Section 19.5.1.19, “Replication and LOAD DATA”.

其他主题Miscellaneous Topics

在 Unix 上,如果您需要 LOAD DATA 从管道读取数据,可以使用以下方法(示例将 / 目录的列表加载到表 db1.t1 中):On Unix, if you need LOAD DATA to read from a pipe, you can use the following technique (the example loads a listing of the / directory into the table db1.t1):

mkfifo /mysql/data/db1/ls.dat
chmod 666 /mysql/data/db1/ls.dat
find / -ls > /mysql/data/db1/ls.dat &
mysql -e "LOAD DATA INFILE 'ls.dat' INTO TABLE t1" db1

在此,您必须在不同的终端运行生成要加载数据的命令和 mysql 命令,或者在后台运行数据生成进程(如前面的示例所示)。如果不这样做,管道会一直阻塞,直到 mysql 进程读取数据。Here you must run the command that generates the data to be loaded and the mysql commands either on separate terminals, or run the data generation process in the background (as shown in the preceding example). If you do not do this, the pipe blocks until data is read by the mysql process.