Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL error: Illegal mix of collations for operation 'UNION'

Tags:

mysql

I am Boxonix!

I am currently making a comment section for my website, and I'm tiny a bit in trouble! This "Illegal mix of collations for operation 'UNION'" pops out when i run this query:

SELECT *
FROM comments
JOIN users ON comments.user_id = users.id
ORDER BY users.id DESC LIMIT $LIMIT1
UNION
SELECT *
FROM comments
JOIN videos ON comments.video_id = videos.id

I am already kind a bit confused, I'm not using MySQL that often!
Please help!

like image 264
user3080291 Avatar asked Dec 08 '13 17:12

user3080291


People also ask

What does illegal mix of collations mean?

An "illegal mix of collations" occurs when an expression compares two strings of different collations but of equal coercibility and the coercibility rules cannot help to resolve the conflict.

What does collate mean in MySQL?

A collation is a set of rules that defines how to compare and sort character strings. Each collation in MySQL belongs to a single character set. Every character set has at least one collation, and most have two or more collations. A collation orders characters based on weights.


3 Answers

You can force collation in SELECT part of query. For example if column videos.comment is utf8_general_ci and comments.comment is utf8_unicode_ci you can force it to be same:

SELECT 
   comment COLLATE utf8_general_ci
FROM comments
UNION
SELECT 
   comment
FROM videos

But this has limited use in case that collations can't be translated exactly as you want.

like image 176
Nikola Loncar Avatar answered Oct 14 '22 01:10

Nikola Loncar


To avoid "Illegal mix of collations for operation 'UNION'" MySQL error you must verify that same-index columns have the same type of collation or encoding.

like image 32
Josafat Avatar answered Oct 14 '22 01:10

Josafat


The problem is that the two sub-queries will have different column sets.

The first sub-query is going to give you all columns from comments and all columns from users. The second sub-query is going to give you all columns from comments and all columns from videos. Unless the two tables users and videos have the exact same column definitions, then the UNION is not going to work.

You need to decide what columns you need from each query and then customise each SELECT ... so that they match.

like image 3
staticsan Avatar answered Oct 14 '22 02:10

staticsan