Merge the values of several rows into a single field

MAZ :

I'm updating a TableA from another TableB with this MySQL script :

UPDATE TableA
JOIN TableB ON TableB.misc = TableA.id
SET TableA.fieldname = TableB.fieldname;

TableB may have many row where we can found TableB.misc = TableA.id, so I need to include this values row on the TableA.fieldname with a comma-separated :

TableB:

+------+-----------+
| misc | fieldname |
+------+-----------+
|   1  |    123    |
+------+-----------+
|   1  |    456    |
+------+-----------+
|   1  |    789    |
+------+-----------+

Needed result on TableA:

+---------+----------------+
|   id    |    fieldname   |
+------+-------------------+
|    1    |   123,456,789  |
+---------+----------------+
Nae :

Then you should group it before joining:

UPDATE TableA
JOIN (
    SELECT misc, GROUP_CONCAT(fieldname) grouped_fieldname
    FROM TableB GROUP BY misc) TableB ON TableB.misc = TableA.id
SET TableA.fieldname = TableB.grouped_fieldname;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=5587&siteId=1