can i use GROUP_CONCAT to update table? I have 2 tables
i
d | label
------------------------------
1 | ravi,rames,raja
------------------------------
2 | ravi
------------------------------
3 | ravi,raja
------------------------------
4 | null
------------------------------
5 | null
------------------------------
6 | rames
------------------------------
and
id | values
------------------------------
12 | raja
------------------------------
13 | rames
------------------------------
14 | ravi
------------------------------
And i want the result like following table–
id | label
------------------------------
1 | 12,13,14
------------------------------
2 | 14
------------------------------
3 | 14,12
------------------------------
4 | null
------------------------------
5 | null
------------------------------
6 | 13
------------------------------
but by using the following query –
SELECT `table1`.`id`, GROUP_CONCAT(`table2`.`id` ORDER BY `table2`.`id`) AS label
FROM `table1`
JOIN `table2` ON FIND_IN_SET(`table2`.`values`, `table1`.`nos`)
GROUP BY `table1`.`id`;
Im getting-
id | label
------------------------------
1 | 12,13,14
------------------------------
2 | 14
------------------------------
3 | 12,14
------------------------------
6 | 13
------------------------------
I want to keep the null value. otherwise the order of rows will be broken. please help.
sorry for the large font 🙁
You just need a
LEFT JOINto preserve the nulls:However, I recommend against updating a table to include comma-separated values in a column. It forces you to use
FIND_IN_SET()when querying it, and breaks the ability to index the column, affecting the performance of your queries. The more sustainable action would be to normalize table1 so that it doesn’t include a comma-separated column.Update:
To use
GROUP_CONCAT()in anUPDATEstatement, you would use a syntax like the following. Substitute your correct table and column names, and in your case, you probably want to replace the entire JOIN subquery with your SELECT statement.So in your case: