字符集转换

Exisi 2023-01-22 15:08:46
Categories: Tags:

语法

CONVERT(expr USING transcoding_name)

 

示例

SELECT CONVERT('test' USING utf8mb4);

SELECT CONVERT(_latin1'Müller' USING utf8mb4);

INSERT INTO utf8mb4_table (utf8mb4_column)

SELECT CONVERT(latin1_column USING utf8mb4) FROM latin1_table;

 

 

 

语法

CONVERT(string, CHAR[(N)] CHARACTER SET charset_name)

CAST(string AS CHAR[(N)] CHARACTER SET charset_name)

示例

SELECT CONVERT('test', CHAR CHARACTER SET utf8mb4);

SELECT CAST('test' AS CHAR CHARACTER SET utf8mb4);

 

 

 

 

 

SELECT CONVERT('test' USING utf8mb4) COLLATE utf8mb4_bin;

SELECT CONVERT('test', CHAR CHARACTERSET utf8mb4) COLLATE utf8mb4_bin;

SELECT CAST('test' AS CHAR CHARACTERSET utf8mb4) COLLATE utf8mb4_bin;

 

SELECT CONVERT('test' USING utf8mb4 COLLATE utf8mb4_bin);

SELECT CONVERT('test', CHAR CHARACTERSET utf8mb4 COLLATE utf8mb4_bin);

SELECT CAST('test' AS CHAR CHARACTERSET utf8mb4 COLLATE utf8mb4_bin);

 

 

 

 

字符串比较的字符集转换

 

 

示例

SELECT 'A' LIKE CONVERT(blob_col USING utf8mb4) FROM tbl_name;

 

示例

SELECT 'A' LIKE CONVERT(blob_col USING utf8mb4) COLLATE utf8mb4_unicode_ci FROM tbl_name;

 

 

示例

mysql> SET @s1 = _latin1 'abc', @s2 = _latin2 'abc';

mysql> SELECT @s1 = @s2;

ERROR 1267 (HY000):Illegal mix of collations (latin1_swedish_ci,IMPLICIT)
and (latin2_general_ci,IMPLICIT) for operation '='

 

示例

mysql> SELECT @s1 = CONVERT(@s2 USING latin1);

+------------------------------------------+

|@s1 = CONVERT(@s2 USING latin1)  |

+------------------------------------------+

|                                                         1 |

+------------------------------------------+

 

示例

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                                                         |

+------------------+---------------------------------------------------+

请注意,如果将BINARYCAST()或CONVERT()应用于索引列,MySQL可能无法有效地使用索引。

 

 

来自 < https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html>