Troubleshooting “Illegal mix of collations” error in mysql

前端 未结 17 2589
一生所求
一生所求 2020-11-22 08:11

Am getting the below error when trying to do a select through a stored procedure in MySQL.

Illegal mix of collations (latin1_general_cs,IMPLICIT) and

17条回答
  •  青春惊慌失措
    2020-11-22 08:39

    I had a similar problem, was trying to use the FIND_IN_SET procedure with a string variable.

    SET @my_var = 'string1,string2';
    SELECT * from my_table WHERE FIND_IN_SET(column_name,@my_var);
    

    and was receiving the error

    Error Code: 1267. Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation 'find_in_set'

    Short answer:

    No need to change any collation_YYYY variables, just add the correct collation next to your variable declaration, i.e.

    SET @my_var = 'string1,string2' COLLATE utf8_unicode_ci;
    SELECT * from my_table WHERE FIND_IN_SET(column_name,@my_var);
    

    Long answer:

    I first checked the collation variables:

    mysql> SHOW VARIABLES LIKE 'collation%';
        +----------------------+-----------------+
        | Variable_name        | Value           |
        +----------------------+-----------------+
        | collation_connection | utf8_general_ci |
        +----------------------+-----------------+
        | collation_database   | utf8_general_ci |
        +----------------------+-----------------+
        | collation_server     | utf8_general_ci |
        +----------------------+-----------------+
    

    Then I checked the table collation:

    mysql> SHOW CREATE TABLE my_table;
    
    CREATE TABLE `my_table` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `column_name` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=125 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    

    This means that my variable was configured with the default collation of utf8_general_ci while my table was configured as utf8_unicode_ci.

    By adding the COLLATE command next to the variable declaration, the variable collation matched the collation configured for the table.

提交回复
热议问题