8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

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

打开官方英文原文 ↗

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

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

14.8.1 字符串比较函数和操作符14.8.1 String Comparison Functions and Operators

表 14.13 字符串比较函数和操作符Table 14.13 String Comparison Functions and Operators

名称Name 说明Description
LIKE 简单的模式匹配Simple pattern matching
NOT LIKE 简单模式匹配的取反Negation of simple pattern matching
STRCMP() 比较两个字符串Compare two strings

如果给字符串函数提供一个二进制字符串作为参数,生成的字符串也是二进制字符串。一个数字转换为字符串后会被视为二进制字符串。这只影响比较。If a string function is given a binary string as an argument, the resulting string is also a binary string. A number converted to a string is treated as a binary string. This affects only comparisons.

通常,如果字符串比较中的任何表达式区分大小写,则比较以区分大小写的方式进行。Normally, if any expression in a string comparison is case-sensitive, the comparison is performed in case-sensitive fashion.

如果从 mysql 客户端内部调用字符串函数,二进制字符串将根据 --binary-as-hex 的值以十六进制表示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。If a string function is invoked from within the mysql client, binary strings 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”.

  • expr LIKE pat [ESCAPE 'escape_char']

    使用 SQL 模式进行模式匹配。返回 1(TRUE)或 0(FALSE)。如果 expr 或 pat 为 NULL,结果为 NULL。Pattern matching using an SQL pattern. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL.

    模式不必是字面字符串。例如,它可以指定为字符串表达式或表列。在后一种情况下,该列必须定义为 MySQL 字符串类型之一(参见 第 13.3 节,“字符串数据类型”)。The pattern need not be a literal string. For example, it can be specified as a string expression or table column. In the latter case, the column must be defined as one of the MySQL string types (see Section 13.3, “String Data Types”).

    根据 SQL 标准,LIKE 是按字符逐个进行匹配的,因此它可能产生与 = 比较操作符不同的结果:Per the SQL standard, LIKE performs matching on a per-character basis, thus it can produce results different from the = comparison operator:

    mysql> SELECT 'ä' LIKE 'ae' COLLATE latin1_german2_ci;
    +-----------------------------------------+
    | 'ä' LIKE 'ae' COLLATE latin1_german2_ci |
    +-----------------------------------------+
    |                                       0 |
    +-----------------------------------------+
    mysql> SELECT 'ä' = 'ae' COLLATE latin1_german2_ci;
    +--------------------------------------+
    | 'ä' = 'ae' COLLATE latin1_german2_ci |
    +--------------------------------------+
    |                                    1 |
    +--------------------------------------+
    

    特别是,尾随空格总是具有重要意义。这不同于使用= 运算符进行的比较,对于非二进制字符串(CHAR、VARCHAR 和 TEXT 值),尾随空格是否重要取决于用于比较的排序规则的填充属性。有关更多信息,请参见 比较中的尾随空格处理。In particular, trailing spaces are always significant. This differs from comparisons performed with the = operator, for which the significance of trailing spaces in nonbinary strings (CHAR, VARCHAR, and TEXT values) depends on the pad attribute of the collation used for the comparison. For more information, see Trailing Space Handling in Comparisons.

    使用 LIKE 时,可以在模式中使用以下两个通配符字符:With LIKE you can use the following two wildcard characters in the pattern:

    • % 匹配任意数量的字符,包括零个字符。% matches any number of characters, even zero characters.

    • _ 精确匹配一个字符。_ matches exactly one character.

    mysql> SELECT 'David!' LIKE 'David_';
            -> 1
    mysql> SELECT 'David!' LIKE '%D%v%';
            -> 1
    

    要测试通配符字符的字面实例,请在其前面加上转义字符。如果未指定 ESCAPE 字符,则默认使用 \,除非启用了 NO_BACKSLASH_ESCAPES SQL 模式。在那种情况下,不使用任何转义字符。To test for literal instances of a wildcard character, precede it by the escape character. If you do not specify the ESCAPE character, \ is assumed, unless the NO_BACKSLASH_ESCAPES SQL mode is enabled. In that case, no escape character is used.

    • \% 匹配一个 % 字符。\% matches one % character.

    • \_ 匹配一个 _ 字符。\_ matches one _ character.

    mysql> SELECT 'David!' LIKE 'David\_';
            -> 0
    mysql> SELECT 'David_' LIKE 'David\_';
            -> 1
    

    要指定不同的转义字符,请使用 ESCAPE 子句:To specify a different escape character, use the ESCAPE clause:

    mysql> SELECT 'David_' LIKE 'David|_' ESCAPE '|';
            -> 1
    

    转义序列应该是一个字符长以指定转义字符,或者为空以表示不使用转义字符。表达式必须在执行时被评估为常量。如果启用了 NO_BACKSLASH_ESCAPES SQL 模式,则序列不能为空。The escape sequence should be one character long to specify the escape character, or empty to specify that no escape character is used. The expression must evaluate as a constant at execution time. If the NO_BACKSLASH_ESCAPES SQL mode is enabled, the sequence cannot be empty.

    以下说明表明,字符串比较不区分大小写,除非其中一个操作数区分大小写(使用区分大小写的排序规则或是二进制字符串):The following statements illustrate that string comparisons are not case-sensitive unless one of the operands is case-sensitive (uses a case-sensitive collation or is a binary string):

    mysql> SELECT 'abc' LIKE 'ABC';
            -> 1
    mysql> SELECT 'abc' LIKE _utf8mb4 'ABC' COLLATE utf8mb4_0900_as_cs;
            -> 0
    mysql> SELECT 'abc' LIKE _utf8mb4 'ABC' COLLATE utf8mb4_bin;
            -> 0
    mysql> SELECT 'abc' LIKE BINARY 'ABC';
            -> 0
    

    作为标准 SQL 的扩展,MySQL 允许在数值表达式上使用 LIKE。As an extension to standard SQL, MySQL permits LIKE on numeric expressions.

    mysql> SELECT 10 LIKE '1%';
            -> 1
    

    在这种情况下,MySQL 会尝试将表达式隐式转换为字符串。请参见 第 14.3 节,“表达式求值中的类型转换”。MySQL attempts in such cases to perform implicit conversion of the expression to a string. See Section 14.3, “Type Conversion in Expression Evaluation”.

    Note

    MySQL 在字符串中使用 C 风格转义语法(例如,\n 表示换行符)。如果你希望 LIKE 字符串包含一个字面量的 \,必须将其重复一次。(除非启用了 NO_BACKSLASH_ESCAPES SQL 模式,此时不使用转义字符。)例如,要搜索 \n,应指定为 \\n。要搜索 \,应指定为 \\\\;这是因为反斜杠首先被解析器去掉一次,然后在模式匹配时再次去掉一次,最终留下一个用于匹配的单个反斜杠。MySQL uses C escape syntax in strings (for example, \n to represent the newline character). If you want a LIKE string to contain a literal \, you must double it. (Unless the NO_BACKSLASH_ESCAPES SQL mode is enabled, in which case no escape character is used.) For example, to search for \n, specify it as \\n. To search for \, specify it as \\\\; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.

    异常:在模式字符串的末尾,反斜杠可以指定为 \\。在字符串的末尾,反斜杠表示它自身,因为后面没有需要转义的内容。假设一个表包含以下值:Exception: At the end of the pattern string, backslash can be specified as \\. At the end of the string, backslash stands for itself because there is nothing following to escape. Suppose that a table contains the following values:

    mysql> SELECT filename FROM t1;
    +--------------+
    | filename     |
    +--------------+
    | C:           |
    | C:\          |
    | C:\Programs  |
    | C:\Programs\ |
    +--------------+
    

    要测试以反斜杠结尾的值,您可以使用以下任一模式来匹配这些值:To test for values that end with backslash, you can match the values using either of the following patterns:

    mysql> SELECT filename, filename LIKE '%\\' FROM t1;
    +--------------+---------------------+
    | filename     | filename LIKE '%\\' |
    +--------------+---------------------+
    | C:           |                   0 |
    | C:\          |                   1 |
    | C:\Programs  |                   0 |
    | C:\Programs\ |                   1 |
    +--------------+---------------------+
    
    mysql> SELECT filename, filename LIKE '%\\\\' FROM t1;
    +--------------+-----------------------+
    | filename     | filename LIKE '%\\\\' |
    +--------------+-----------------------+
    | C:           |                     0 |
    | C:\          |                     1 |
    | C:\Programs  |                     0 |
    | C:\Programs\ |                     1 |
    +--------------+-----------------------+
    
  • expr NOT LIKE pat [ESCAPE 'escape_char']

    这与 NOT (expr LIKE pat [ESCAPE 'escape_char']) 相同。This is the same as NOT (expr LIKE pat [ESCAPE 'escape_char']).

    Note

    涉及包含 NULL 列的 NOT LIKE 比较的聚合查询可能产生意想不到的结果。例如,考虑以下表和数据:Aggregate queries involving NOT LIKE comparisons with columns containing NULL may yield unexpected results. For example, consider the following table and data:

    CREATE TABLE foo (bar VARCHAR(10));
    
    INSERT INTO foo VALUES (NULL), (NULL);
    

    查询 SELECT COUNT(*) FROM foo WHERE bar LIKE '%baz%'; 返回 0。你可能会以为 SELECT COUNT(*) FROM foo WHERE bar NOT LIKE '%baz%'; 会返回 2。然而,情况并非如此:第二个查询返回 0。这是因为 NULL NOT LIKE expr 总是返回 NULL,无论 expr 的值是什么。对于涉及 NULL 的聚合查询,以及使用 NOT RLIKE 或 NOT REGEXP 的比较,也同样适用。在这种情况下,你必须显式地使用 OR(而不是 AND)来测试 NOT NULL,如下所示:The query SELECT COUNT(*) FROM foo WHERE bar LIKE '%baz%'; returns 0. You might assume that SELECT COUNT(*) FROM foo WHERE bar NOT LIKE '%baz%'; would return 2. However, this is not the case: The second query returns 0. This is because NULL NOT LIKE expr always returns NULL, regardless of the value of expr. The same is true for aggregate queries involving NULL and comparisons using NOT RLIKE or NOT REGEXP. In such cases, you must test explicitly for NOT NULL using OR (and not AND), as shown here:

    SELECT COUNT(*) FROM foo WHERE bar NOT LIKE '%baz%' OR bar IS NULL;
    
  • STRCMP(expr1,expr2)

    STRCMP() 如果字符串相同则返回 0,如果第一个参数根据当前排序规则小于第二个参数则返回 -1,如果任意参数为 NULL 则返回 NULL。否则返回 1。STRCMP() returns 0 if the strings are the same, -1 if the first argument is smaller than the second according to the current sort order, and NULL if either argument is NULL. It returns 1 otherwise.

    mysql> SELECT STRCMP('text', 'text2');
            -> -1
    mysql> SELECT STRCMP('text2', 'text');
            -> 1
    mysql> SELECT STRCMP('text', 'text');
            -> 0
    

    STRCMP() 使用参数的校对规则进行比较。STRCMP() performs the comparison using the collation of the arguments.

    mysql> SET @s1 = _utf8mb4 'x' COLLATE utf8mb4_0900_ai_ci;
    mysql> SET @s2 = _utf8mb4 'X' COLLATE utf8mb4_0900_ai_ci;
    mysql> SET @s3 = _utf8mb4 'x' COLLATE utf8mb4_0900_as_cs;
    mysql> SET @s4 = _utf8mb4 'X' COLLATE utf8mb4_0900_as_cs;
    mysql> SELECT STRCMP(@s1, @s2), STRCMP(@s3, @s4);
    +------------------+------------------+
    | STRCMP(@s1, @s2) | STRCMP(@s3, @s4) |
    +------------------+------------------+
    |                0 |               -1 |
    +------------------+------------------+
    

    如果排序规则不兼容,则必须将其中一个参数转换为与另一个兼容。请参见第 12.8.4 节,“表达式中的排序规则强制性”。If the collations are incompatible, one of the arguments must be converted to be compatible with the other. See Section 12.8.4, “Collation Coercibility in Expressions”.

    mysql> SET @s1 = _utf8mb4 'x' COLLATE utf8mb4_0900_ai_ci;
    mysql> SET @s2 = _utf8mb4 'X' COLLATE utf8mb4_0900_ai_ci;
    mysql> SET @s3 = _utf8mb4 'x' COLLATE utf8mb4_0900_as_cs;
    mysql> SET @s4 = _utf8mb4 'X' COLLATE utf8mb4_0900_as_cs;
    -->
    mysql> SELECT STRCMP(@s1, @s3);
    ERROR 1267 (HY000): Illegal mix of collations (utf8mb4_0900_ai_ci,IMPLICIT)
    and (utf8mb4_0900_as_cs,IMPLICIT) for operation 'strcmp'
    mysql> SELECT STRCMP(@s1, @s3 COLLATE utf8mb4_0900_ai_ci);
    +---------------------------------------------+
    | STRCMP(@s1, @s3 COLLATE utf8mb4_0900_ai_ci) |
    +---------------------------------------------+
    |                                           0 |
    +---------------------------------------------+