Search code examples
mysqlsqlmergemultiple-columnstemporary

MySQL Merge multiple colums into one 'temporary' column


I was curious about the fact, if it's possible to merge multiple columns (seperated by a comma, or something else) into one column.

So for instance, i have these tables (languages):

language_id    |   language_iso  
    1                   NL
    2                   EN
    3                   GT
    4                   EN

(Domains)

domain_id    |   domain_name  
    1                example

And another table which links the language to a webdomain

languagetodomain_id    |   languagetodomain_lang    |   languagetodomain_domain
    1                               1                            1
    2                               2                            1
    3                               4                            1
    4                               3                            1

And retrieve them in this order (ONE column as a reminder)

domain_id    |   domain_name    | TemporaryColumn
    1                example         {1,2,4,3}

Solution

  • This should work:

    SELECT Domains.*, CONCAT('{',GROUP_CONCAT(languagetodomain_lang),'}') AS TemporaryColumn
    FROM Domains
    JOIN LanguageToDomain ON LanguageToDomain.languagetodomain_domain = Domains.domain_id
    GROUP BY domain_id
    

    The function GROUP_CONCAT groups values separating them by a comma. I added the brackets using normal CONCAT function. You need to group on the domain_id so it takes all the languagetodomain_lang for each domain that you have.

    I've guessed the table name for languagetodomain as you didn't provide it.