小编典典

MySQL选择特定的行值作为列名

sql

这是我的基本participants表(显示为关联数组):

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

在另一个名为的表上,participants_custom我可以添加多个属于participants一行的自定义数据。像这样:

[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

我目前正在制作join,但它只会增加nameparticipant_iddata给我行。我想要的是我的查询返回如下内容:

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

行值name变成一列,而value,它就是值。 我该怎么做?


阅读 182

收藏
2021-03-10

共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;
2021-03-10