表 14.12 字符串函数和运算符Table 14.12 String Functions and Operators
| 名称Name | 说明Description |
|---|---|
ASCII() |
返回最左边字符的数值Return numeric value of left-most character |
BIN() |
返回包含数字二进制表示的字符串Return a string containing binary representation of a number |
BIT_LENGTH() |
返回参数的位长度Return length of argument in bits |
CHAR() |
返回传入的每个整数对应的字符Return the character for each integer passed |
CHAR_LENGTH() |
返回参数中的字符数Return number of characters in argument |
CHARACTER_LENGTH() |
CHAR_LENGTH() 的同义词Synonym for CHAR_LENGTH() |
CONCAT() |
返回连接的字符串Return concatenated string |
CONCAT_WS() |
返回带分隔符的连接Return concatenate with separator |
ELT() |
返回索引号处的字符串Return string at index number |
EXPORT_SET() |
返回一个字符串,对于值位中设置的每一位,你得到一个“开”字符串,对于未设置的每一位,你得到一个“关”字符串Return a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string |
FIELD() |
第一个参数在后续参数中的索引(位置)Index (position) of first argument in subsequent arguments |
FIND_IN_SET() |
第一个参数在第二个参数中的索引(位置)Index (position) of first argument within second argument |
FORMAT() |
返回格式化为指定小数位数的数字Return a number formatted to specified number of decimal places |
FROM_BASE64() |
解码 base64 编码的字符串并返回结果Decode base64 encoded string and return result |
HEX() |
十六进制表示十进制或字符串值Hexadecimal representation of decimal or string value |
INSERT() |
在指定位置插入子字符串,最多指定字符数Insert substring at specified position up to specified number of characters |
INSTR() |
返回子字符串首次出现的索引Return the index of the first occurrence of substring |
LCASE() |
LOWER()的同义词Synonym for LOWER() |
LEFT() |
返回指定的最左边的字符数Return the leftmost number of characters as specified |
LENGTH() |
返回字符串的字节长度Return the length of a string in bytes |
LIKE |
简单的模式匹配Simple pattern matching |
LOAD_FILE() |
加载指定文件Load the named file |
LOCATE() |
返回子字符串首次出现的位置Return the position of the first occurrence of substring |
LOWER() |
将参数转换为小写Return the argument in lowercase |
LPAD() |
返回字符串参数,并在左侧用指定的字符串填充Return the string argument, left-padded with the specified string |
LTRIM() |
移除前导空格Remove leading spaces |
MAKE_SET() |
返回一组以逗号分隔的字符串,这些字符串对应的位在 bits 中已设置Return a set of comma-separated strings that have the corresponding bit in bits set |
MATCH() |
执行全文搜索Perform full-text search |
MID() |
从指定位置返回子字符串Return a substring starting from the specified position |
NOT LIKE |
简单模式匹配的取反Negation of simple pattern matching |
NOT REGEXPNOT REGEXP |
REGEXP 的否定Negation of REGEXP |
OCT() |
返回包含数字八进制表示的字符串Return a string containing octal representation of a number |
OCTET_LENGTH() |
LENGTH() 的同义词Synonym for LENGTH() |
ORD() |
返回参数最左边字符的字符编码Return character code for leftmost character of the argument |
POSITION() |
LOCATE() 的同义词Synonym for LOCATE() |
QUOTE() |
转义参数以在 SQL 语句中使用Escape the argument for use in an SQL statement |
REGEXPREGEXP |
字符串是否匹配正则表达式Whether string matches regular expression |
REGEXP_INSTR() |
子字符串匹配正则表达式的起始索引Starting index of substring matching regular expression |
REGEXP_LIKE() |
字符串是否匹配正则表达式Whether string matches regular expression |
REGEXP_REPLACE() |
替换与正则表达式匹配的子字符串Replace substrings matching regular expression |
REGEXP_SUBSTR() |
返回匹配正则表达式的子字符串Return substring matching regular expression |
REPEAT() |
重复指定次数的字符串Repeat a string the specified number of times |
REPLACE()REPLACE() |
替换指定字符串的出现Replace occurrences of a specified string |
REVERSE() |
反转字符串中的字符Reverse the characters in a string |
RIGHT() |
返回指定的最右边的字符数Return the specified rightmost number of characters |
RLIKE |
字符串是否匹配正则表达式Whether string matches regular expression |
RPAD() |
将字符串附加指定次数Append string the specified number of times |
RTRIM() |
移除尾随空格Remove trailing spaces |
SOUNDEX() |
返回一个 soundex 字符串Return a soundex string |
SOUNDS LIKESOUNDS LIKE |
比较声音Compare sounds |
SPACE() |
返回指定数量空格的字符串Return a string of the specified number of spaces |
STRCMP() |
比较两个字符串Compare two strings |
SUBSTR() |
返回指定的子字符串Return the substring as specified |
SUBSTRING() |
返回指定的子字符串Return the substring as specified |
SUBSTRING_INDEX() |
从字符串中返回指定分隔符出现次数之前的子字符串Return a substring from a string before the specified number of occurrences of the delimiter |
TO_BASE64() |
将参数转换为 base-64 字符串后返回Return the argument converted to a base-64 string |
TRIM() |
去掉首尾空格Remove leading and trailing spaces |
UCASE() |
UPPER() 的同义词Synonym for UPPER() |
UNHEX() |
返回包含数字的十六进制表示的字符串Return a string containing hex representation of a number |
UPPER() |
转换为大写Convert to uppercase |
WEIGHT_STRING() |
返回字符串的权重字符串Return the weight string for a string |
如果结果的长度大于系统变量 max_allowed_packet 的值,则返回字符串类型的函数会返回 NULL。请参见 第 7.1.1 节,“配置服务器”。String-valued functions return NULL if the
length of the result would be greater than the value of the
max_allowed_packet system
variable. See Section 7.1.1, “Configuring the Server”.
对于操作字符串位置的函数,第一个位置编号为 1。For functions that operate on string positions, the first position is numbered 1.
对于接受长度参数的函数,非整数参数会四舍五入到最接近的整数。For functions that take length arguments, noninteger arguments are rounded to the nearest integer.
返回字符串
str最左边字符的数值。如果str是空字符串,则返回0。如果str为NULL,则返回NULL。ASCII()适用于 8 位字符。Returns the numeric value of the leftmost character of the stringstr. Returns0ifstris the empty string. ReturnsNULLifstrisNULL.ASCII()works for 8-bit characters.mysql>
SELECT ASCII('2');-> 50 mysql>SELECT ASCII(2);-> 50 mysql>SELECT ASCII('dx');-> 100返回
N的二进制值的字符串表示形式,其中N是一个 longlong (BIGINT) 数字。这相当于CONV(。如果N,10,2)N为NULL,则返回NULL。Returns a string representation of the binary value ofN, whereNis a longlong (BIGINT) number. This is equivalent toCONV(. ReturnsN,10,2)NULLifNisNULL.mysql>
SELECT BIN(12);-> '1100'返回字符串
str的长度(以比特为单位)。如果str为NULL,则返回NULL。Returns the length of the stringstrin bits. ReturnsNULLifstrisNULL.mysql>
SELECT BIT_LENGTH('text');-> 32CHAR(N,... [USING charset_name])CHAR(N,... [USINGcharset_name])CHAR()将每个参数N解释为整数,并返回由这些整数的码值对应的字符组成的字符串。NULL值会被跳过。CHAR()interprets each argumentNas an integer and returns a string consisting of the characters given by the code values of those integers.NULLvalues are skipped.mysql>
SELECT CHAR(77,121,83,81,'76');+--------------------------------------------------+ | CHAR(77,121,83,81,'76') | +--------------------------------------------------+ | 0x4D7953514C | +--------------------------------------------------+ 1 row in set (0.00 sec) mysql>SELECT CHAR(77,77.3,'77.3');+--------------------------------------------+ | CHAR(77,77.3,'77.3') | +--------------------------------------------+ | 0x4D4D4D | +--------------------------------------------+ 1 row in set (0.00 sec)默认情况下,
CHAR()返回二进制字符串。要生成指定字符集的字符串,请使用可选的USING子句:By default,CHAR()returns a binary string. To produce a string in a given character set, use the optionalUSINGclause:mysql>
SELECT CHAR(77,121,83,81,'76' USING utf8mb4);+---------------------------------------+ | CHAR(77,121,83,81,'76' USING utf8mb4) | +---------------------------------------+ | MySQL | +---------------------------------------+ 1 row in set (0.00 sec) mysql>SELECT CHAR(77,77.3,'77.3' USING utf8mb4);+------------------------------------+ | CHAR(77,77.3,'77.3' USING utf8mb4) | +------------------------------------+ | MMM | +------------------------------------+ 1 row in set, 1 warning (0.00 sec) mysql>SHOW WARNINGS;+---------+------+-------------------------------------------+ | Level | Code | Message | +---------+------+-------------------------------------------+ | Warning | 1292 | Truncated incorrect INTEGER value: '77.3' | +---------+------+-------------------------------------------+ 1 row in set (0.00 sec)如果提供了
USING并且结果字符串对于指定字符集是非法的,将会发出警告。此外,如果启用了严格 SQL 模式,CHAR()的结果将变为NULL。IfUSINGis given and the result string is illegal for the given character set, a warning is issued. Also, if strict SQL mode is enabled, the result fromCHAR()becomesNULL.如果在 mysql 客户端内调用
CHAR(),二进制字符串将根据--binary-as-hex的值以十六进制显示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — The MySQL 命令行客户端”。IfCHAR()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”.CHAR()参数大于 255 时会转换为多个结果字节。例如,CHAR(256)等同于CHAR(1,0),而CHAR(256*256)等同于CHAR(1,0,0):CHAR()arguments larger than 255 are converted into multiple result bytes. For example,CHAR(256)is equivalent toCHAR(1,0), andCHAR(256*256)is equivalent toCHAR(1,0,0):mysql>
SELECT HEX(CHAR(1,0)), HEX(CHAR(256));+----------------+----------------+ | HEX(CHAR(1,0)) | HEX(CHAR(256)) | +----------------+----------------+ | 0100 | 0100 | +----------------+----------------+ 1 row in set (0.00 sec) mysql>SELECT HEX(CHAR(1,0,0)), HEX(CHAR(256*256));+------------------+--------------------+ | HEX(CHAR(1,0,0)) | HEX(CHAR(256*256)) | +------------------+--------------------+ | 010000 | 010000 | +------------------+--------------------+ 1 row in set (0.00 sec)CHAR_LENGTH(str)CHAR_LENGTH(str)返回字符串
str的长度,以代码点计算。一个多字节字符算作一个代码点。这意味着,对于一个包含两个三字节字符的字符串,LENGTH()返回6,而CHAR_LENGTH()返回2,如下面所示:Returns the length of the stringstr, measured in code points. A multibyte character counts as a single code point. This means that, for a string containing two 3-byte characters,LENGTH()returns6, whereasCHAR_LENGTH()returns2, as shown here:mysql>
SET @dolphin:='海豚';Query OK, 0 rows affected (0.01 sec) mysql>SELECT LENGTH(@dolphin), CHAR_LENGTH(@dolphin);+------------------+-----------------------+ | LENGTH(@dolphin) | CHAR_LENGTH(@dolphin) | +------------------+-----------------------+ | 6 | 2 | +------------------+-----------------------+ 1 row in set (0.00 sec)CHAR_LENGTH()如果str为NULL,则返回NULL。CHAR_LENGTH()returnsNULLifstrisNULL.CHARACTER_LENGTH(str)CHARACTER_LENGTH(str)CHARACTER_LENGTH()是CHAR_LENGTH()的同义词。CHARACTER_LENGTH()is a synonym forCHAR_LENGTH().返回通过连接参数得到的字符串。可以有一个或多个参数。如果所有参数都是非二进制字符串,结果是非二进制字符串。如果参数中包含任何二进制字符串,结果将是二进制字符串。数值参数会被转换为其等效的非二进制字符串形式。Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent nonbinary string form.
CONCAT()如果任意参数为NULL,则返回NULL。CONCAT()returnsNULLif any argument isNULL.mysql>
SELECT CONCAT('My', 'S', 'QL');-> 'MySQL' mysql>SELECT CONCAT('My', NULL, 'QL');-> NULL mysql>SELECT CONCAT(14.3);-> '14.3'对于带引号的字符串,可以通过将字符串放在一起进行连接:For quoted strings, concatenation can be performed by placing the strings next to each other:
mysql>
SELECT 'My' 'S' 'QL';-> 'MySQL'如果在 mysql 客户端中调用
CONCAT(),二进制字符串结果会根据--binary-as-hex的值以十六进制显示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfCONCAT()is invoked from within the mysql client, binary string results display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.CONCAT_WS(separator,str1,str2,...)CONCAT_WS(separator,str1,str2,...)CONCAT_WS()代表带分隔符的连接,是CONCAT()的一种特殊形式。第一个参数是其余参数的分隔符。该分隔符将添加在要连接的字符串之间。分隔符可以是字符串,其余参数也可以是字符串。如果分隔符是NULL,结果就是NULL。CONCAT_WS()stands for Concatenate With Separator and is a special form ofCONCAT(). The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the separator isNULL, the result isNULL.mysql>
SELECT CONCAT_WS(',', 'First name', 'Second name', 'Last Name');-> 'First name,Second name,Last Name' mysql>SELECT CONCAT_WS(',', 'First name', NULL, 'Last Name');-> 'First name,Last Name'CONCAT_WS()不会跳过空字符串。然而,它会跳过分隔符参数之后的任何NULL值。CONCAT_WS()does not skip empty strings. However, it does skip anyNULLvalues after the separator argument.ELT()返回字符串列表中的第N个元素:如果N=1,则返回str1,如果N=2,则返回str2,以此类推。如果N小于1、大于参数数量,或为NULL,则返回NULL。ELT()是FIELD()的补充函数。ELT()returns theNth element of the list of strings:str1ifN=1,str2ifN=2, and so on. ReturnsNULLifNis less than1, greater than the number of arguments, orNULL.ELT()is the complement ofFIELD().mysql>
SELECT ELT(1, 'Aa', 'Bb', 'Cc', 'Dd');-> 'Aa' mysql>SELECT ELT(4, 'Aa', 'Bb', 'Cc', 'Dd');-> 'Dd'EXPORT_SET(bits,on,off[,separator[,number_of_bits]])返回一个字符串,对于
bits中设置为 1 的每个位,返回一个on字符串,对于每个位未设置的,返回一个off字符串。bits中的位从右到左(从低位到高位)进行检查。字符串从左到右添加到结果中,以separator字符串分隔(默认是逗号字符,)。检查的位数由number_of_bits指定,如果未指定,默认值为 64。如果number_of_bits大于 64,则会自动裁剪为 64。它被视为无符号整数,因此值为 −1 实际上等同于 64。Returns a string such that for every bit set in the valuebits, you get anonstring and for every bit not set in the value, you get anoffstring. Bits inbitsare examined from right to left (from low-order to high-order bits). Strings are added to the result from left to right, separated by theseparatorstring (the default being the comma character,). The number of bits examined is given bynumber_of_bits, which has a default of 64 if not specified.number_of_bitsis silently clipped to 64 if larger than 64. It is treated as an unsigned integer, so a value of −1 is effectively the same as 64.mysql>
SELECT EXPORT_SET(5,'Y','N',',',4);-> 'Y,N,Y,N' mysql>SELECT EXPORT_SET(6,'1','0',',',10);-> '0,1,1,0,0,0,0,0,0,0'返回
str在str1、str2、str3、...列表中的索引(位置)。如果未找到str,则返回0。Returns the index (position) ofstrin thestr1,str2,str3,...list. Returns0ifstris not found.如果
FIELD()的所有参数都是字符串,则所有参数按字符串进行比较。如果所有参数都是数字,则按数字进行比较。否则,参数将按双精度浮点数进行比较。If all arguments toFIELD()are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.如果
str是NULL,返回值为0,因为NULL与任何值进行相等比较都会失败。FIELD()是ELT()的补充函数。IfstrisNULL, the return value is0becauseNULLfails equality comparison with any value.FIELD()is the complement ofELT().mysql>
SELECT FIELD('Bb', 'Aa', 'Bb', 'Cc', 'Dd', 'Ff');-> 2 mysql>SELECT FIELD('Gg', 'Aa', 'Bb', 'Cc', 'Dd', 'Ff');-> 0如果字符串
str位于由N个子字符串组成的字符串列表strlist中,则返回 1 到N范围内的值。字符串列表是由,字符分隔的子字符串组成的字符串。如果第一个参数是常量字符串,第二个参数是类型为SET的列,则FIND_IN_SET()函数会优化为使用位运算。如果str不在strlist中,或者strlist是空字符串,则返回0。如果任一参数为NULL,则返回NULL。如果第一个参数包含逗号 (,) 字符,则此函数不能正常工作。Returns a value in the range of 1 toNif the stringstris in the string liststrlistconsisting ofNsubstrings. A string list is a string composed of substrings separated by,characters. If the first argument is a constant string and the second is a column of typeSET, theFIND_IN_SET()function is optimized to use bit arithmetic. Returns0ifstris not instrlistor ifstrlistis the empty string. ReturnsNULLif either argument isNULL. This function does not work properly if the first argument contains a comma (,) character.mysql>
SELECT FIND_IN_SET('b','a,b,c,d');-> 2Formats the number
Xto a format like'#,###,###.##', rounded toDdecimal places, and returns the result as a string. IfDis0, the result has no decimal point or fractional part. IfX或者DisNULL, the function returnsNULL.Formats the numberXto a format like'#,###,###.##', rounded toDdecimal places, and returns the result as a string. IfDis0, the result has no decimal point or fractional part. IfXorDisNULL, the function returnsNULL.可选的第三个参数允许指定一个用于结果数字的小数点、千位分隔符和分隔符之间分组的区域设置。允许的区域设置值与
lc_time_names系统变量的合法值相同(参见 第 12.16 节,“MySQL 服务器区域设置支持”)。如果区域设置为NULL或未指定,则默认区域设置为'en_US'。The optional third parameter enables a locale to be specified to be used for the result number's decimal point, thousands separator, and grouping between separators. Permissible locale values are the same as the legal values for thelc_time_namessystem variable (see Section 12.16, “MySQL Server Locale Support”). If the locale isNULLor not specified, the default locale is'en_US'.mysql>
SELECT FORMAT(12332.123456, 4);-> '12,332.1235' mysql>SELECT FORMAT(12332.1,4);-> '12,332.1000' mysql>SELECT FORMAT(12332.2,0);-> '12,332' mysql>SELECT FORMAT(12332.2,2,'de_DE');-> '12.332,20'接受一个使用
TO_BASE64()使用的 base-64 编码规则编码的字符串,并返回解码后的二进制字符串。如果参数为NULL或不是有效的 base-64 字符串,则结果为NULL。有关编码和解码规则的详细信息,请参见TO_BASE64()的说明。Takes a string encoded with the base-64 encoded rules used byTO_BASE64()and returns the decoded result as a binary string. The result isNULLif the argument isNULLor not a valid base-64 string. See the description ofTO_BASE64()for details about the encoding and decoding rules.mysql>
SELECT TO_BASE64('abc'), FROM_BASE64(TO_BASE64('abc'));-> 'JWJj', 'abc'如果在
FROM_BASE64()中从 mysql 客户端调用,二进制字符串将以十六进制符号显示。您可以通过在启动 mysql 客户端时,将--binary-as-hex设置为0来禁用此行为。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfFROM_BASE64()is invoked from within the mysql client, binary strings display using hexadecimal notation. You can disable this behavior by setting the value of the--binary-as-hexto0when starting the mysql client. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.对于字符串参数
str,HEX()返回str的十六进制字符串表示形式,其中str中每个字符的每个字节都被转换为两个十六进制数字。(因此,多字节字符将变为多于两个数字。)该操作的逆操作由UNHEX()函数执行。For a string argumentstr,HEX()returns a hexadecimal string representation ofstrwhere each byte of each character instris converted to two hexadecimal digits. (Multibyte characters therefore become more than two digits.) The inverse of this operation is performed by theUNHEX()function.对于数值参数
N,HEX()返回将N作为 longlong (BIGINT) 数处理后的十六进制字符串表示。这等同于CONV(。该操作的逆运算由N,10,16)CONV(HEX(执行。For a numeric argumentN),16,10)N,HEX()returns a hexadecimal string representation of the value ofNtreated as a longlong (BIGINT) number. This is equivalent toCONV(. The inverse of this operation is performed byN,10,16)CONV(HEX(.N),16,10)对于
NULL参数,此函数返回NULL。For aNULLargument, this function returnsNULL.mysql>
SELECT X'616263', HEX('abc'), UNHEX(HEX('abc'));-> 'abc', 616263, 'abc' mysql>SELECT HEX(255), CONV(HEX(255),16,10);-> 'FF', 255返回字符串
str,其中从位置pos开始、长度为len的子字符串被字符串newstr替换。如果pos不在字符串长度范围内,则返回原始字符串。如果len不在剩余字符串的长度范围内,则从位置pos起替换剩余的字符串。如果任何参数为NULL,则返回NULL。Returns the stringstr, with the substring beginning at positionposandlencharacters long replaced by the stringnewstr. Returns the original string ifposis not within the length of the string. Replaces the rest of the string from positionposiflenis not within the length of the rest of the string. ReturnsNULLif any argument isNULL.mysql>
SELECT INSERT('Quadratic', 3, 4, 'What');-> 'QuWhattic' mysql>SELECT INSERT('Quadratic', -1, 4, 'What');-> 'Quadratic' mysql>SELECT INSERT('Quadratic', 3, 100, 'What');-> 'QuWhat'此函数支持多字节。This function is multibyte safe.
返回子字符串
substr在字符串str中首次出现的位置。这与LOCATE()的两个参数形式相同,只是参数顺序相反。Returns the position of the first occurrence of substringsubstrin stringstr. This is the same as the two-argument form ofLOCATE(), except that the order of the arguments is reversed.mysql>
SELECT INSTR('foobarbar', 'bar');-> 4 mysql>SELECT INSTR('xbar', 'foobar');-> 0此函数支持多字节字符,并且仅在至少一个参数是二进制字符串时区分大小写。如果任一参数为
NULL,此函数返回NULL。This function is multibyte safe, and is case-sensitive only if at least one argument is a binary string. If either argument isNULL, this functions returnsNULL.LCASE()是LOWER()的同义词。LCASE()is a synonym forLOWER().在视图中使用
LCASE()时,在存储视图定义时会被重写为LOWER()。(Bug #12844279)LCASE()used in a view is rewritten asLOWER()when storing the view's definition. (Bug #12844279)返回字符串
str的最左边len个字符,如果任一参数为NULL,则返回NULL。Returns the leftmostlencharacters from the stringstr, orNULLif any argument isNULL.mysql>
SELECT LEFT('foobarbar', 5);-> 'fooba'此函数支持多字节。This function is multibyte safe.
返回字符串
str的长度,以字节为单位。多字节字符计为多个字节。这意味着对于包含五个 2 字节字符的字符串,LENGTH()返回10,而CHAR_LENGTH()返回5。如果str为NULL,则返回NULL。Returns the length of the stringstr, measured in bytes. A multibyte character counts as multiple bytes. This means that for a string containing five 2-byte characters,LENGTH()returns10, whereasCHAR_LENGTH()returns5. ReturnsNULLifstrisNULL.mysql>
SELECT LENGTH('text');-> 4NoteOpenGIS 空间函数
Length()在 MySQL 中被命名为ST_Length()。TheLength()OpenGIS spatial function is namedST_Length()in MySQL.读取文件并将文件内容作为字符串返回。要使用此函数,文件必须位于服务器主机上,必须指定文件的完整路径名,并且必须拥有
FILE权限。文件必须可被服务器读取,且其大小小于max_allowed_packet字节。如果secure_file_priv系统变量设置为非空目录名,则要加载的文件必须位于该目录中。Reads the file and returns the file contents as a string. To use this function, the file must be located on the server host, you must specify the full path name to the file, and you must have theFILEprivilege. The file must be readable by the server and its size less thanmax_allowed_packetbytes. If thesecure_file_privsystem variable is set to a nonempty directory name, the file to be loaded must be located in that directory.如果文件不存在或由于不满足前述条件而无法读取,函数将返回
NULL。If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returnsNULL.character_set_filesystem系统变量控制以字面字符串提供的文件名的解释。Thecharacter_set_filesystemsystem variable controls interpretation of file names that are given as literal strings.mysql>
UPDATE tSET blob_col=LOAD_FILE('/tmp/picture')WHERE id=1;LOCATE(,substr,str)LOCATE(substr,str,pos)第一个语法返回子字符串
substr在字符串str中第一次出现的位置。第二个语法返回子字符串substr在字符串str中第一次出现的位置,从位置pos开始。如果substr不在str中,则返回0。如果任何参数为NULL,则返回NULL。The first syntax returns the position of the first occurrence of substringsubstrin stringstr. The second syntax returns the position of the first occurrence of substringsubstrin stringstr, starting at positionpos. Returns0ifsubstris not instr. ReturnsNULLif any argument isNULL.mysql>
SELECT LOCATE('bar', 'foobarbar');-> 4 mysql>SELECT LOCATE('xbar', 'foobar');-> 0 mysql>SELECT LOCATE('bar', 'foobarbar', 5);-> 7这个函数支持多字节,并且只有在至少一个参数是二进制字符串时才区分大小写。This function is multibyte safe, and is case-sensitive only if at least one argument is a binary string.
返回字符串
str,其中所有字符根据当前字符集映射转换为小写,如果str为NULL,则返回NULL。默认字符集为utf8mb4。Returns the stringstrwith all characters changed to lowercase according to the current character set mapping, orNULLifstrisNULL. The default character set isutf8mb4.mysql>
SELECT LOWER('QUADRATICALLY');-> 'quadratically'LOWER()(以及UPPER())在应用于二进制字符串(BINARY、VARBINARY、BLOB)时无效。要对二进制字符串进行字母大小写转换,首先使用适合字符串中存储数据的字符集将其转换为非二进制字符串:LOWER()(andUPPER()) are ineffective when applied to binary strings (BINARY,VARBINARY,BLOB). To perform lettercase conversion of a binary string, first convert it to a nonbinary string using a character set appropriate for the data stored in the string:mysql>
SET @str = BINARY 'New York';mysql>SELECT LOWER(@str), LOWER(CONVERT(@str USING utf8mb4));+-------------+------------------------------------+ | LOWER(@str) | LOWER(CONVERT(@str USING utf8mb4)) | +-------------+------------------------------------+ | New York | new york | +-------------+------------------------------------+对于 Unicode 字符集的排序规则,
LOWER()和UPPER()会根据排序规则名称中的 Unicode 排序算法(UCA)版本进行工作,如果没有指定版本,则使用 UCA 4.0.0。例如,utf8mb4_0900_ai_ci和utf8mb3_unicode_520_ci分别按照 UCA 9.0.0 和 5.2.0 工作,而utf8mb3_unicode_ci则按照 UCA 4.0.0 工作。请参阅 第 12.10.1 节,“Unicode 字符集”。For collations of Unicode character sets,LOWER()andUPPER()work according to the Unicode Collation Algorithm (UCA) version in the collation name, if there is one, and UCA 4.0.0 if no version is specified. For example,utf8mb4_0900_ai_ciandutf8mb3_unicode_520_ciwork according to UCA 9.0.0 and 5.2.0, respectively, whereasutf8mb3_unicode_ciworks according to UCA 4.0.0. See Section 12.10.1, “Unicode Character Sets”.此函数支持多字节。This function is multibyte safe.
LCASE()在视图中使用时会重写为LOWER()。LCASE()used within views is rewritten asLOWER().返回字符串
str,左侧用字符串padstr填充至长度len个字符。如果str长度超过len,返回值将被截短为len个字符。Returns the stringstr, left-padded with the stringpadstrto a length oflencharacters. Ifstris longer thanlen, the return value is shortened tolencharacters.mysql>
SELECT LPAD('hi',4,'??');-> '??hi' mysql>SELECT LPAD('hi',1,'??');-> 'h'如果其任意参数为
NULL,返回NULL。ReturnsNULLif any of its arguments areNULL.返回字符串
str,并删除前导空格字符。如果str为NULL,则返回NULL。Returns the stringstrwith leading space characters removed. ReturnsNULLifstrisNULL.mysql>
SELECT LTRIM(' barbar');-> 'barbar'此函数支持多字节。This function is multibyte safe.
返回一个设定值(一个包含以
,字符分隔的子字符串的字符串),该值由在bits中相应位被设置的字符串组成。str1对应位 0,str2对应位 1,依此类推。NULL值在str1、str2、...中不会附加到结果中。Returns a set value (a string containing substrings separated by,characters) consisting of the strings that have the corresponding bit inbitsset.str1corresponds to bit 0,str2to bit 1, and so on.NULLvalues instr1,str2,...are not appended to the result.mysql>
SELECT MAKE_SET(1,'a','b','c');-> 'a' mysql>SELECT MAKE_SET(1 | 4,'hello','nice','world');-> 'hello,world' mysql>SELECT MAKE_SET(1 | 4,'hello','nice',NULL,'world');-> 'hello' mysql>SELECT MAKE_SET(0,'a','b','c');-> ''MID(,str,pos)MID(,strFROMpos)MID(,str,pos,len)MID(strFROMposFORlen)MID(是str,pos,len)SUBSTRING(的同义词。str,pos,len)MID(is a synonym forstr,pos,len)SUBSTRING(.str,pos,len)返回
N的八进制值的字符串表示形式,其中N是一个 longlong (BIGINT) 数字。这相当于CONV(。如果N,10,8)N为NULL,则返回NULL。Returns a string representation of the octal value ofN, whereNis a longlong (BIGINT) number. This is equivalent toCONV(. ReturnsN,10,8)NULLifNisNULL.mysql>
SELECT OCT(12);-> '14'OCTET_LENGTH()是LENGTH()的同义词。OCTET_LENGTH()is a synonym forLENGTH().如果字符串
str的最左边字符是多字节字符,则返回该字符的代码,该代码通过使用其组成字节的数值计算,公式如下:If the leftmost character of the stringstris a multibyte character, returns the code for that character, calculated from the numeric values of its constituent bytes using this formula:(1st byte code) + (2nd byte code * 256) + (3rd byte code * 256^2) ...
如果最左边的字符不是多字节字符,
ORD()返回的值与ASCII()函数返回的值相同。如果str为NULL,该函数返回NULL。If the leftmost character is not a multibyte character,ORD()returns the same value as theASCII()function. The function returnsNULLifstrisNULL.mysql>
SELECT ORD('2');-> 50POSITION(substr IN str)是LOCATE(的同义词。substr,str)POSITION(is a synonym forsubstrINstr)LOCATE(.substr,str)对字符串加引号,以生成可在 SQL 语句中作为正确转义数据值使用的结果。返回的字符串会被单引号包围,并且每个反斜杠 (
\)、单引号 (')、ASCIINUL和 Control+Z 前都会加上反斜杠。如果参数为NULL,则返回值为单词 “NULL”,不加单引号。Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (\), single quote ('), ASCIINUL, and Control+Z preceded by a backslash. If the argument isNULL, the return value is the word “NULL” without enclosing single quotation marks.mysql>
SELECT QUOTE('Don\'t!');-> 'Don\'t!' mysql>SELECT QUOTE(NULL);-> NULL有关比较,请参阅在 C API 中对字面字符串加引号的规则,见 第 11.1.1 节,“字符串字面值”,以及 mysql_real_escape_string_quote()。For comparison, see the quoting rules for literal strings and within the C API in Section 11.1.1, “String Literals”, and mysql_real_escape_string_quote().
REPEAT(str,count)REPEAT(str,count)返回一个由字符串
str重复count次组成的字符串。如果count小于 1,则返回空字符串。如果str或count为NULL,则返回NULL。Returns a string consisting of the stringstrrepeatedcounttimes. Ifcountis less than 1, returns an empty string. ReturnsNULLifstrorcountisNULL.mysql>
SELECT REPEAT('MySQL', 3);-> 'MySQLMySQLMySQL'REPLACE(str,from_str,to_str)REPLACE(str,from_str,to_str)返回字符串
str,其中所有出现的字符串from_str都被字符串to_str替换。REPLACE()在搜索from_str时执行区分大小写的匹配。Returns the stringstrwith all occurrences of the stringfrom_strreplaced by the stringto_str.REPLACE()performs a case-sensitive match when searching forfrom_str.mysql>
SELECT REPLACE('www.mysql.com', 'w', 'Ww');-> 'WwWwWw.mysql.com'此函数对多字节安全。如果其任何参数为
NULL,则返回NULL。This function is multibyte safe. It returnsNULLif any of its arguments areNULL.返回字符串
str的字符顺序反转后的结果,如果str为NULL则返回NULL。Returns the stringstrwith the order of the characters reversed, orNULLifstrisNULL.mysql>
SELECT REVERSE('abc');-> 'cba'此函数支持多字节。This function is multibyte safe.
返回字符串
str最右侧的len个字符,如果任何参数为NULL则返回NULL。Returns the rightmostlencharacters from the stringstr, orNULLif any argument isNULL.mysql>
SELECT RIGHT('foobarbar', 4);-> 'rbar'此函数支持多字节。This function is multibyte safe.
返回字符串
str,用字符串padstr在右侧填充至长度为len个字符。如果str长度超过len,返回值会被截断为len个字符。如果str、padstr或len为NULL,函数返回NULL。Returns the stringstr, right-padded with the stringpadstrto a length oflencharacters. Ifstris longer thanlen, the return value is shortened tolencharacters. Ifstr,padstr, orlenisNULL, the function returnsNULL.mysql>
SELECT RPAD('hi',5,'?');-> 'hi???' mysql>SELECT RPAD('hi',1,'?');-> 'h'此函数支持多字节。This function is multibyte safe.
返回去掉尾部空格的字符串
str。Returns the stringstrwith trailing space characters removed.mysql>
SELECT RTRIM('barbar ');-> 'barbar'此函数支持多字节,并且如果
str为NULL,则返回NULL。This function is multibyte safe, and returnsNULLifstrisNULL.从
str返回一个 soundex 字符串,如果str为NULL,则返回NULL。两个发音几乎相同的字符串应该具有相同的 soundex 字符串。标准的 soundex 字符串长度为四个字符,但SOUNDEX()函数返回的是任意长度的字符串。您可以在结果上使用SUBSTRING()来获取标准的 soundex 字符串。str中的所有非字母字符将被忽略。所有 A-Z 范围之外的国际字母字符都被视为元音。Returns a soundex string fromstr, orNULLifstrisNULL. Two strings that sound almost the same should have identical soundex strings. A standard soundex string is four characters long, but theSOUNDEX()function returns an arbitrarily long string. You can useSUBSTRING()on the result to get a standard soundex string. All nonalphabetic characters instrare ignored. All international alphabetic characters outside the A-Z range are treated as vowels.Important在使用
SOUNDEX()时,你应该注意以下限制:When usingSOUNDEX(), you should be aware of the following limitations:此函数按当前实现方式,仅适用于英文字符串。其他语言的字符串可能无法产生可靠的结果。This function, as currently implemented, is intended to work well with strings that are in the English language only. Strings in other languages may not produce reliable results.
此函数不能保证对使用多字节字符集(包括
utf-8)的字符串提供一致的结果。有关更多信息,请参阅 Bug #22638。This function is not guaranteed to provide consistent results with strings that use multibyte character sets, includingutf-8. See Bug #22638 for more information.
mysql>
SELECT SOUNDEX('Hello');-> 'H400' mysql>SELECT SOUNDEX('Quadratically');-> 'Q36324'Note此函数实现了原始的 Soundex 算法,而不是更流行的增强版本(也由 D. Knuth 描述)。区别在于,原始版本先丢弃元音再去除重复,而增强版本先去除重复再丢弃元音。This function implements the original Soundex algorithm, not the more popular enhanced version (also described by D. Knuth). The difference is that original version discards vowels first and duplicates second, whereas the enhanced version discards duplicates first and vowels second.
expr1 SOUNDS LIKE expr2expr1SOUNDS LIKEexpr2这与
SOUNDEX(expr1) = SOUNDEX(expr2)相同。This is the same asSOUNDEX(.expr1) = SOUNDEX(expr2)返回一个由
N个空格字符组成的字符串,如果N为NULL,则返回NULL。Returns a string consisting ofNspace characters, orNULLifNisNULL.mysql>
SELECT SPACE(6);-> ' 'SUBSTR(,str,pos)SUBSTR(str FROM pos),SUBSTR(,str,pos,len)SUBSTR(str FROM pos FOR len)SUBSTR(,str,pos)SUBSTR(,strFROMpos)SUBSTR(,str,pos,len)SUBSTR(strFROMposFORlen)SUBSTR()是SUBSTRING()的同义词。SUBSTR()is a synonym forSUBSTRING().SUBSTRING(,str,pos)SUBSTRING(str FROM pos),SUBSTRING(,str,pos,len)SUBSTRING(str FROM pos FOR len)SUBSTRING(,str,pos)SUBSTRING(,strFROMpos)SUBSTRING(,str,pos,len)SUBSTRING(strFROMposFORlen)没有
len参数的形式会从字符串str的位置pos开始返回一个子字符串。有len参数的形式会从字符串str的位置pos开始返回一个长度为len的子字符串。使用FROM的形式是标准 SQL 语法。也可以为pos使用负值。在这种情况下,子字符串的起始位置是从字符串末尾向前数pos个字符,而不是从开头开始。pos的任何形式都可以使用负值。pos的值为 0 时会返回一个空字符串。The forms without alenargument return a substring from stringstrstarting at positionpos. The forms with alenargument return a substringlencharacters long from stringstr, starting at positionpos. The forms that useFROMare standard SQL syntax. It is also possible to use a negative value forpos. In this case, the beginning of the substring isposcharacters from the end of the string, rather than the beginning. A negative value may be used forposin any of the forms of this function. A value of 0 forposreturns an empty string.对于所有形式的
SUBSTRING(),要提取子字符串的起始字符位置从1开始计算。For all forms ofSUBSTRING(), the position of the first character in the string from which the substring is to be extracted is reckoned as1.mysql>
SELECT SUBSTRING('Quadratically',5);-> 'ratically' mysql>SELECT SUBSTRING('foobarbar' FROM 4);-> 'barbar' mysql>SELECT SUBSTRING('Quadratically',5,6);-> 'ratica' mysql>SELECT SUBSTRING('Sakila', -3);-> 'ila' mysql>SELECT SUBSTRING('Sakila', -5, 3);-> 'aki' mysql>SELECT SUBSTRING('Sakila' FROM -4 FOR 2);-> 'ki'此函数对多字节安全。如果其任何参数为
NULL,则返回NULL。This function is multibyte safe. It returnsNULLif any of its arguments areNULL.如果
len小于 1,结果为空字符串。Iflenis less than 1, the result is the empty string.SUBSTRING_INDEX(str,delim,count)返回字符串
str中在分隔符delim出现count次之前的子字符串。如果count为正数,返回最后一个分隔符(从左边开始计数)左侧的所有内容。如果count为负数,返回最后一个分隔符(从右边开始计数)右侧的所有内容。SUBSTRING_INDEX()在搜索delim时执行区分大小写的匹配。Returns the substring from stringstrbeforecountoccurrences of the delimiterdelim. Ifcountis positive, everything to the left of the final delimiter (counting from the left) is returned. Ifcountis negative, everything to the right of the final delimiter (counting from the right) is returned.SUBSTRING_INDEX()performs a case-sensitive match when searching fordelim.mysql>
SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);-> 'www.mysql' mysql>SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);-> 'mysql.com'此函数支持多字节。This function is multibyte safe.
SUBSTRING_INDEX()如果其任何参数为NULL,则返回NULL。SUBSTRING_INDEX()returnsNULLif any of its arguments areNULL.将字符串参数转换为 Base64 编码形式,并以连接的字符集和排序规则返回结果作为字符串。如果参数不是字符串,则在转换之前会先将其转换为字符串。如果参数为
NULL,结果为NULL。Base64 编码的字符串可以使用FROM_BASE64()函数进行解码。Converts the string argument to base-64 encoded form and returns the result as a character string with the connection character set and collation. If the argument is not a string, it is converted to a string before conversion takes place. The result isNULLif the argument isNULL. Base-64 encoded strings can be decoded using theFROM_BASE64()function.mysql>
SELECT TO_BASE64('abc'), FROM_BASE64(TO_BASE64('abc'));-> 'JWJj', 'abc'存在不同的 base-64 编码方案。以下是
TO_BASE64()和FROM_BASE64()使用的编码和解码规则:Different base-64 encoding schemes exist. These are the encoding and decoding rules used byTO_BASE64()andFROM_BASE64():字母表值 62 的编码为
'+'。The encoding for alphabet value 62 is'+'.字母表值 63 的编码为
'/'。The encoding for alphabet value 63 is'/'.编码输出由 4 个可打印字符组成的一组组字符构成。输入数据的每 3 个字节使用 4 个字符进行编码。如果最后一组不完整,则用
'='字符填充至长度为 4。Encoded output consists of groups of 4 printable characters. Each 3 bytes of the input data are encoded using 4 characters. If the last group is incomplete, it is padded with'='characters to a length of 4.在每 76 个字符的编码输出后会添加一个换行符,以将长输出分成多行。A newline is added after each 76 characters of encoded output to divide long output into multiple lines.
解码时会识别并忽略换行符、回车、制表符和空格。Decoding recognizes and ignores newline, carriage return, tab, and space.
TRIM([{BOTH | LEADING | TRAILING} [,remstr] FROM]str)TRIM([remstrFROM]str)返回删除了所有
remstr前缀或后缀的字符串str。如果没有指定BOTH、LEADING或TRAILING,则默认为BOTH。remstr是可选的,如果未指定,则删除空格。Returns the stringstrwith allremstrprefixes or suffixes removed. If none of the specifiersBOTH,LEADING, orTRAILINGis given,BOTHis assumed.remstris optional and, if not specified, spaces are removed.mysql>
SELECT TRIM(' bar ');-> 'bar' mysql>SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx');-> 'barxxx' mysql>SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx');-> 'bar' mysql>SELECT TRIM(TRAILING 'xyz' FROM 'barxxyz');-> 'barx'此函数对多字节安全。如果其任何参数为
NULL,则返回NULL。This function is multibyte safe. It returnsNULLif any of its arguments areNULL.UCASE()是UPPER()的同义词。UCASE()is a synonym forUPPER().UCASE()在视图中使用时会被重写为UPPER()。UCASE()used within views is rewritten asUPPER().对于字符串参数
str,UNHEX(将参数中的每对字符解释为十六进制数,并将其转换为该数字表示的字节。返回值是二进制字符串。For a string argumentstr)str,UNHEX(interprets each pair of characters in the argument as a hexadecimal number and converts it to the byte represented by the number. The return value is a binary string.str)mysql>
SELECT UNHEX('4D7953514C');-> 'MySQL' mysql>SELECT X'4D7953514C';-> 'MySQL' mysql>SELECT UNHEX(HEX('string'));-> 'string' mysql>SELECT HEX(UNHEX('1267'));-> '1267'参数字符串中的字符必须是合法的十六进制数字:
'0'..'9'、'A'..'F'、'a'..'f'。如果参数包含任何非十六进制数字,或参数本身为NULL,结果为NULL:The characters in the argument string must be legal hexadecimal digits:'0'..'9','A'..'F','a'..'f'. If the argument contains any nonhexadecimal digits, or is itselfNULL, the result isNULL:mysql>
SELECT UNHEX('GG');+-------------+ | UNHEX('GG') | +-------------+ | NULL | +-------------+ mysql>SELECT UNHEX(NULL);+-------------+ | UNHEX(NULL) | +-------------+ | NULL | +-------------+如果传递给
UNHEX()的参数是BINARY列,也可能会出现NULL结果,因为在存储时值会用0x00字节进行填充,但在检索时这些字节不会被去掉。例如,'41'存储到CHAR(3)列时会存为'41 ',且检索出来时为'41'(尾随填充空格被去掉),因此该列值调用UNHEX()返回X'41'。相比之下,'41'存储到BINARY(3)列时会存为'41\0',检索出来时为'41\0'(尾随填充的0x00字节未被去掉)。'\0'不是合法的十六进制数字,因此该列值调用UNHEX()返回NULL。ANULLresult can also occur if the argument toUNHEX()is aBINARYcolumn, because values are padded with0x00bytes when stored but those bytes are not stripped on retrieval. For example,'41'is stored into aCHAR(3)column as'41 'and retrieved as'41'(with the trailing pad space stripped), soUNHEX()for the column value returnsX'41'. By contrast,'41'is stored into aBINARY(3)column as'41\0'and retrieved as'41\0'(with the trailing pad0x00byte not stripped).'\0'is not a legal hexadecimal digit, soUNHEX()for the column value returnsNULL.对于数值参数
N,HEX(的逆操作不是通过N)UNHEX()来执行的。请改用CONV(HEX(。有关N),16,10)HEX()的说明,请参见描述。For a numeric argumentN, the inverse ofHEX(is not performed byN)UNHEX(). UseCONV(HEX(instead. See the description ofN),16,10)HEX().如果在 mysql 客户端中调用
UNHEX(),二进制字符串将根据--binary-as-hex的值以十六进制表示。有关该选项的更多信息,请参阅 第 6.5.1 节,“mysql — The MySQL 命令行客户端”。IfUNHEX()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”.返回将字符串
str中所有字符根据当前字符集映射转换为大写后的字符串,如果str为NULL则返回NULL。默认字符集是utf8mb4。Returns the stringstrwith all characters changed to uppercase according to the current character set mapping, orNULLifstrisNULL. The default character set isutf8mb4.mysql>
SELECT UPPER('Hej');-> 'HEJ'请参阅
LOWER()的描述,其中包含也适用于UPPER()的信息。这包括关于如何对二进制字符串(BINARY、VARBINARY、BLOB)进行大小写转换的方法,这些函数对其不起作用,以及关于 Unicode 字符集大小写折叠的信息。See the description ofLOWER()for information that also applies toUPPER(). This included information about how to perform lettercase conversion of binary strings (BINARY,VARBINARY,BLOB) for which these functions are ineffective, and information about case folding for Unicode character sets.此函数支持多字节。This function is multibyte safe.
UCASE()在视图中使用时会被重写为UPPER()。UCASE()used within views is rewritten asUPPER().WEIGHT_STRING(str[AS {CHAR|BINARY}(N)] [flags])此函数返回输入字符串的权重字符串。返回值是一个二进制字符串,表示该字符串的比较和排序值,如果参数为
NULL,则返回NULL。它具有以下属性:This function returns the weight string for the input string. The return value is a binary string that represents the comparison and sorting value of the string, orNULLif the argument isNULL. It has these properties:如果
WEIGHT_STRING(=str1)WEIGHT_STRING(,那么str2)str1 = str2(str1和str2被视为相等)IfWEIGHT_STRING(=str1)WEIGHT_STRING(, thenstr2)(str1=str2str1andstr2are considered equal)如果
WEIGHT_STRING(<str1)WEIGHT_STRING(,那么str2)str1 < str2(str1排在str2之前)IfWEIGHT_STRING(<str1)WEIGHT_STRING(, thenstr2)(str1<str2str1sorts beforestr2)
WEIGHT_STRING()是一个用于调试的函数,供内部使用。它的行为可能在不同的 MySQL 版本之间无通知地变化。它可用于排序规则的测试和调试,特别是在你添加新的排序规则时。参见 第 12.14 节,“向字符集添加排序规则”。WEIGHT_STRING()is a debugging function intended for internal use. Its behavior can change without notice between MySQL versions. It can be used for testing and debugging of collations, especially if you are adding a new collation. See Section 12.14, “Adding a Collation to a Character Set”.此列表简要总结了论点。更多细节请参见列表后的讨论。This list briefly summarizes the arguments. More details are given in the discussion following the list.
str:输入的字符串表达式。str: The input string expression.AS子句:可选;将输入字符串转换为指定的类型和长度。ASclause: Optional; cast the input string to a given type and length.flags:可选;未使用。flags: Optional; unused.
输入字符串,
str,是一个字符串表达式。如果输入的是非二进制(字符)字符串,例如CHAR、VARCHAR或TEXT值,则返回值包含该字符串的排序权重。如果输入的是二进制(字节)字符串,例如BINARY、VARBINARY或BLOB值,则返回值与输入相同(二进制字符串中每个字节的权重就是字节值)。如果输入是NULL,WEIGHT_STRING()返回NULL。The input string,str, is a string expression. If the input is a nonbinary (character) string such as aCHAR,VARCHAR, orTEXTvalue, the return value contains the collation weights for the string. If the input is a binary (byte) string such as aBINARY,VARBINARY, orBLOBvalue, the return value is the same as the input (the weight for each byte in a binary string is the byte value). If the input isNULL,WEIGHT_STRING()returnsNULL.示例:Examples:
mysql>
SET @s = _utf8mb4 'AB' COLLATE utf8mb4_0900_ai_ci;mysql>SELECT @s, HEX(@s), HEX(WEIGHT_STRING(@s));+------+---------+------------------------+ | @s | HEX(@s) | HEX(WEIGHT_STRING(@s)) | +------+---------+------------------------+ | AB | 4142 | 1C471C60 | +------+---------+------------------------+mysql>
SET @s = _utf8mb4 'ab' COLLATE utf8mb4_0900_ai_ci;mysql>SELECT @s, HEX(@s), HEX(WEIGHT_STRING(@s));+------+---------+------------------------+ | @s | HEX(@s) | HEX(WEIGHT_STRING(@s)) | +------+---------+------------------------+ | ab | 6162 | 1C471C60 | +------+---------+------------------------+mysql>
SET @s = CAST('AB' AS BINARY);mysql>SELECT @s, HEX(@s), HEX(WEIGHT_STRING(@s));+------+---------+------------------------+ | @s | HEX(@s) | HEX(WEIGHT_STRING(@s)) | +------+---------+------------------------+ | AB | 4142 | 4142 | +------+---------+------------------------+mysql>
SET @s = CAST('ab' AS BINARY);mysql>SELECT @s, HEX(@s), HEX(WEIGHT_STRING(@s));+------+---------+------------------------+ | @s | HEX(@s) | HEX(WEIGHT_STRING(@s)) | +------+---------+------------------------+ | ab | 6162 | 6162 | +------+---------+------------------------+前面的示例使用
HEX()来显示WEIGHT_STRING()的结果。由于结果是二进制值,当结果包含不可打印的值时,HEX()特别有用,可以将其以可打印的形式显示:The preceding examples useHEX()to display theWEIGHT_STRING()result. Because the result is a binary value,HEX()can be especially useful when the result contains nonprinting values, to display it in printable form:mysql>
SET @s = CONVERT(X'C39F' USING utf8mb4) COLLATE utf8mb4_czech_ci;mysql>SELECT HEX(WEIGHT_STRING(@s));+------------------------+ | HEX(WEIGHT_STRING(@s)) | +------------------------+ | 0FEA0FEA | +------------------------+对于非
NULL的返回值,如果其长度在VARBINARY的最大长度之内,则值的数据类型为VARBINARY,否则数据类型为BLOB。For non-NULLreturn values, the data type of the value isVARBINARYif its length is within the maximum length forVARBINARY, otherwise the data type isBLOB.可以使用
AS子句将输入字符串转换为非二进制或二进制字符串,并强制其为给定长度:TheASclause may be given to cast the input string to a nonbinary or binary string and to force it to a given length:AS CHAR(将字符串转换为非二进制字符串,并在右侧用空格填充至N)N个字符的长度。N必须至少为 1。如果N小于输入字符串的长度,则字符串会被截断至N个字符。截断不会产生警告。AS CHAR(casts the string to a nonbinary string and pads it on the right with spaces to a length ofN)Ncharacters.Nmust be at least 1. IfNis less than the length of the input string, the string is truncated toNcharacters. No warning occurs for truncation.AS BINARY(类似,但将字符串转换为二进制字符串,N)N以字节为单位(不是字符),并且填充使用0x00字节(不是空格)。AS BINARY(is similar but casts the string to a binary string,N)Nis measured in bytes (not characters), and padding uses0x00bytes (not spaces).
mysql>
SET NAMES 'latin1';mysql>SELECT HEX(WEIGHT_STRING('ab' AS CHAR(4)));+-------------------------------------+ | HEX(WEIGHT_STRING('ab' AS CHAR(4))) | +-------------------------------------+ | 41422020 | +-------------------------------------+ mysql>SET NAMES 'utf8mb4';mysql>SELECT HEX(WEIGHT_STRING('ab' AS CHAR(4)));+-------------------------------------+ | HEX(WEIGHT_STRING('ab' AS CHAR(4))) | +-------------------------------------+ | 1C471C60 | +-------------------------------------+mysql>
SELECT HEX(WEIGHT_STRING('ab' AS BINARY(4)));+---------------------------------------+ | HEX(WEIGHT_STRING('ab' AS BINARY(4))) | +---------------------------------------+ | 61620000 | +---------------------------------------+flags子句目前未使用。Theflagsclause currently is unused.如果从 mysql 客户端内部调用
WEIGHT_STRING(),则二进制字符串将根据--binary-as-hex的值以十六进制表示。有关该选项的更多信息,请参阅 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfWEIGHT_STRING()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”.