Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: UPDATE with a JOIN and a GROUP_CONCAT

Is this possible?

I have 2 tables, Customers and Orders. Now I want to fill a column in Customers with all order id's of that customer (comma separated).

I tried something like this, but it doesnt work:

UPDATE customers AS c
LEFT JOIN orders AS o ON o.customerid=c.customerid
SET c.orders = GROUP_CONCAT(DISTINCT o.orderid)

I get 'Invalid use of group function'.

PS. I know it's better to always dynamically get the GROUP_CONCAT values in a SELECT/JOIN, but I'm just wondering if I can fill this column in some way.

like image 389
Dylan Avatar asked May 23 '11 16:05

Dylan


People also ask

What does Group_concat do in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

Is there a limit to Group_concat?

The GROUP_CONCAT() function has a default length of 1024 characters, which is controlled by the global variable group_concat_max_len . If the joined values length is greater than the group_concat_max_len value, then the result string will be truncated.


2 Answers

None of the given answers here were working for me, possibly because my case was more complicated (I needed more than one join), so I used Dennis' solution but split it into a temporary table:

CREATE TEMPORARY TABLE version_lookup
SELECT pduid, group_concat(version ORDER BY version SEPARATOR ',') AS 'versions'
     from items GROUP BY pduid;

UPDATE 
items i, version_lookup
SET i.versions = version_lookup.versions
WHERE version_lookup.pduid = i.pduid;
like image 76
Marcus Downing Avatar answered Oct 16 '22 22:10

Marcus Downing


You will need to add an order by in the group_concat as shown in the example below

Note: group_concat(version ORDER BY version SEPARATOR ',')

UPDATE 
items i,
(SELECT pduid, group_concat(version ORDER BY version SEPARATOR ',') AS 'versions'
     from items GROUP BY pduid) AS version_lookup
SET i.versions = version_lookup.versions
WHERE version_lookup.pduid = i.pduid
like image 27
Dennis Avatar answered Oct 16 '22 22:10

Dennis