在 MYSQL 中写入动态枢轴

Write dynamic pivot in MYSQL

这是我的数据透视代码。我想把它转换成动态的..

我试过了,它显示错误..

SELECT  id,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Household'
             THEN answer.text
             ELSE NULL 
         END
     ) AS Household,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Dependents' 
             THEN answer.text
             ELSE NULL 
         END
     ) AS Dependents,
     GROUP_CONCAT(
         CASE 
             WHEN question.question_name = 'Generation'
             THEN answer.text
            ELSE NULL 
         END
     ) AS Generation
   
FROM user_answers
inner join answer on user_answers.answer_id=answer.answer_id
inner join question on answer.question_id=question.question_id
GROUP BY id

代码有效。我想将其转换为动态转换。我试过了。但不工作

SET @sql = NULL;
SELECT
  GROUP_CONCAT(
      'case when question.question_name = ''',
      question.question_name,
      ''' then answer.text ELSE 0  end) AS `',
      question_name, '`'
  ) INTO @sql
FROM  answer
inner join question on answer.question_id=question.question_id;

SET @sql = CONCAT('SELECT id, ', @sql, ' 
                  FROM user_answers
                    inner join answer on user_answers.answer_id=answer.answer_id
                    inner join question on answer.question_id=question.question_id
                    GROUP BY id');

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

显示错误

PREPARE stmt FROM @sql  Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS `Dependents`,case when question.question_name = 'Dependents' then answer.te' at line 1    0.000 sec

本博客中的代码将生成所需的查询,然后执行它: http://mysql.rjweb.org/doc.php/pivot

必须使用存储过程 -- 这就是导致您收到错误的原因。