MySQL splits and merges values

I have a [mapping] table with two columns like below

id  | values
1   | 1,2
2   | 1,2,3
3   | 1,1
4   | 1,1,2

and the other table [map] is similar to this

sno | values
1   | Test
2   | Hello
3   | Hai

My expected result

id  | values
1   | Test,Hello
2   | Test,Hello,Hai
3   | Test,Test
4   | Test,Test,Hello

Is it possible? If possible, someone can create a request for me.

+4
source share
2 answers

You can use MySQL FIND_IN_SET()to join tables and GROUP_CONCAT()to match values:

SELECT s.sno,GROUP_CONCAT(s.values) as `values` 
FROM mapping t
INNER JOIN map s ON(FIND_IN_SET(s.id,t.values))
GROUP BY s.sno

Note. . You should know that this is a very bad database structure. This can lead to much more complex queries and make you complicate the situation. You have to "Normalize" your data, split it and put each IDin a separate record!

+6
source
SELECT
    `ids`.`id`,
    GROUP_CONCAT(`values`.`texts`) AS texts
FROM
    `ids`
INNER JOIN `values` ON FIND_IN_SET(`values`.`id`, `ids`.`values`)
GROUP BY
    `ids`.`id`

:

+2

Source: https://habr.com/ru/post/1652420/


All Articles