MySQL selects specific row values ​​as column names

Here is my base table participants(displayed as an associative array):

[id] => 1
[campaign_id] => 41
[firstname] => Jeff
[lastname] => Berube

In another table named participants_customI can add some user data belonging to the row participants. Like this:

[id] => 51
[participant_id] => 1
[name] => textfield_bh423vjhgv
[data] => qwerty1

[id] => 52
[participant_id] => 1
[name] => textfield_IDRr2kzjZR59Xjw
[data] => qwerty2

[id] => 53
[participant_id] => 1
[name] => textfield_6kj5bhjjg
[data] => qwerty3

I am currently creating join, but it only adds rows name, participant_idand datato my row. I want my query to return something like this:

[id] => 1
[campaign_id] => 41
[firstname] => Jeff
[lastname] => Berube
[textfield_bh423vjhgv] => qwerty1
[textfield_IDRr2kzjZR59Xjw] => qwerty2
[textfield_6kj5bhjjg] => qwerty3

Where a row value namebecomes a column, and valuea value. How to do it?

I found this and this , which was unsuccessful. I find a way that will work with my situation. Thanks for any help.

+1
1
SELECT  a.ID,
        a.Campaign_ID,
        a.FirstName,
        a.LastName,
        MAX(CASE WHEN b.data = 'qwerty1' THEN b.Name END) qwerty1,
        MAX(CASE WHEN b.data = 'qwerty2' THEN b.Name END) qwerty2,
        MAX(CASE WHEN b.data = 'qwerty3' THEN b.Name END) qwerty3
FROM    Participants a
        INNER JOIN Participants_Custom b
            ON a.ID = b.Participant_ID
GROUP   BY  a.ID,
            a.Campaign_ID,
            a.FirstName,
            a.LastName

1

data , sql .

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN b.data = ''',
      data,
      ''' THEN b.Name ELSE NULL END) AS ',
      CONCAT('`',data, '`')
    )
  ) INTO @sql
FROM Participants_Custom;

SET @sql = CONCAT('SELECT  a.ID,
                           a.Campaign_ID,
                           a.FirstName,
                           a.LastName,', @sql, 
                  'FROM     Participants a
                            INNER JOIN Participants_Custom b
                                ON a.ID = b.Participant_ID
                    GROUP   BY  a.ID,
                                a.Campaign_ID,
                                a.FirstName,
                                a.LastName');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
+2

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


All Articles