尝试使用存储过程在 MySQL 中创建 PIVOT,不会添加仅包含空记录的列

Trying to create a PIVOT in MySQL with a stored procedure, won't add columns that only have null records

好的,所以我有三个 table 正在努力组合以创建我的枢轴 table。为简单起见,我将仅引用为此使用的字段。

员工->userTblID,名字,姓氏

lms__trainings->trainingID, trainingName

lms__complete->completeID, trainingID, employeeID(userTblID)

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(b.trainingID = ''',F.trainingID, ''', b.completionDate, NULL)) AS ''', F.trainingName,"'")) INTO @sql FROM lms__trainings AS F INNER JOIN lms__complete AS G ON F.trainingID=G.trainingID;
SET @sql = CONCAT('SELECT a.userTblID, a.firstName, a.lastName, ', @sql, ' FROM employees AS a LEFT JOIN lms__complete AS b ON a.userTblID=b.employeeID WHERE a.cloudID=1 GROUP BY a.userTblID ORDER BY a.lastName');
PREPARE stmt FROM @sql;
EXECUTE stmt;

它生成 PIVOT table 很好,但它只包括在 lms__complete 中有关联记录的 trainingName 列。如果我从第 2 行中删除内部连接或将其更改为左连接(在我看来这不会将其限制为 lms__complete 条目并为您提供 lms__trainings 中的所有 trainingNames)它会给出好的旧1064 错误。

我知道它只是没有通过该过程发送所有 trainingID。我认为我在第 3 行的 LEFT JOIN 应该是 lms__trainings 和 lms__complete 之间的 UNION 的 LEFT JOIN,但最后我没有在 google 中输入正确的搜索参数几天找到我需要的东西。

Solorflare 真的在这里给出了答案。 诀窍是克服 group_concat_max_len.

的默认值

我通过设置

做到了这一点
SET SESSION group_concat_max_len = 5000;

所以我的存储过程现在看起来像

SET @sql = NULL;
SET SESSION group_concat_max_len = 5000;

SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(b.trainingID = ''',F.trainingID, ''', b.completionDate, NULL)) AS ''', F.trainingName,"'")) INTO @sql FROM lms__trainings AS F LEFT JOIN lms__complete AS G ON F.trainingID=G.trainingID;

SET @sql = CONCAT('SELECT a.userTblID, a.firstName, a.lastName, ', @sql, ' FROM employees AS a LEFT JOIN lms__complete AS b ON a.userTblID=b.employeeID WHERE a.cloudID=1 GROUP BY a.userTblID ORDER BY a.lastName');

PREPARE stmt FROM @sql;

EXECUTE stmt;