Illegal mix of collations (...) and (...) for operation without modifying the table structure processing method

Disclaimer: This article is a blogger hanchao5272 original articles, please indicate the source and leave the original link address, thank you! https://blog.csdn.net/hanchao5272/article/details/90344022

Brief

SQL compare the two fields, an error occurs.

# 无需在意逻辑
select *
from article As ar left join author AS au on ar.author_id = au.id
where ar.author <> au.name;

error

Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,IMPLICIT) for operation '<>'

Error Analysis

The cause of the error:

  • Table articleof authorcharacter set field is utf8mb4_general_ci.
  • Table authorof namecharacter set field is utf8mb4_unicode_ci.
  • Field different character sets can not 直接be compared.

Solution

The fundamental solution is to modify the table structure by DDL, to match the field type.

Sometimes, however, probably because conditions can not be DDL operations.

The following provides a solution does not modify the table structure: by castconversion type built-in functions (not the only method, for example convertthe function may be).

# 无需在意逻辑
select *
from article As ar left join author AS au on ar.author_id = au.id
where CAST(ar.author AS char) <> CAST(au.name AS char);

Syntax of the cast function

CAST(field AS type)

Wherein optional typefollows:

  • CHAR Character
  • DATE Date type
  • DATETIME The date and time type
  • DECIMAL float type
  • SIGNED int
  • TIME Time Type

Guess you like

Origin blog.csdn.net/hanchao5272/article/details/90344022
Recommended