Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql GROUP_CONCAT duplicates

I make my join from a farmTOanimal table like this. There is a similar farmTotool table

id | FarmID  | animal  1 |    1    | cat  2 |    1    | dog 

When I join my tables in a view, I get a result that looks like this

FarmID | animal | tool    1   |  cat   | shovel    1   |  dog   | shovel    1   |  cat   | bucket    1   |  dog   | bucket 

Now, I do GROUP BY FarmID, and GROUP_CONCAT(animal) and GROUP_CONCAT(tool), i get

FarmID |     animals     |         tools   1    | cat,dog,cat,dog | shovel,shovel,bucket,bucket 

But, what I really want is a result that looks like this. How can I do it?

FarmID | animals |    tools   1    | cat,dog | shovel,bucket 
like image 997
Matt Avatar asked Dec 30 '10 09:12

Matt


People also ask

What does Group_concat do in MySQL?

GROUP_CONCAT is a function which concatenates/merges the data from multiple rows into one field. It is a GROUP BY function which returns a string if the group contains at least 1 non-null value, if it does not, it returns a Null value.

Is there a length limit to Group_concat?

Show activity on this post. I'm using GROUP_CONCAT() in a MySQL query to convert multiple rows into a single string. However, the maximum length of the result of this function is 1024 characters.

Can we use Group_concat in SQL Server?

The SQL Server Equivalent to GROUP_CONCAT() This function allows you to return a result set as a comma-separated list, as opposed to listing each row as a separate row (as with a normal result set).


1 Answers

You need to use the DISTINCT option:

GROUP_CONCAT(DISTINCT animal) 
like image 196
grahamparks Avatar answered Oct 20 '22 12:10

grahamparks