MySQL动态数据透视表没有给出正确的结果

时间:2017-10-25 19:34:38

标签: mysql sql pivot pivot-table

我有点像SQL菜鸟,但我正在尝试在三个表之间编写一个支点。我有以下查询,除了MAX调用之外它完美地工作。它会导致我的值小于默认值被覆盖。我有下面的表格截图。关于如何解决这个问题的任何想法?

SET @sql = NULL;
SELECT 
    GROUP_CONCAT(DISTINCT
        CONCAT(
            'MAX(IF(cc.company_config_key_id  = ', cck.id, ', cc.config_value, \'', cck.default, '\')) AS ', cck.company_config_key
        )
    ) INTO @sql
    FROM company_config cc
    LEFT JOIN company_config_key cck
    ON cck.id = cc.company_config_key_id;
SET @sql = CONCAT('SELECT co.id, co.name, ', @sql, ' FROM companies co LEFT JOIN company_config cc ON cc.company_id = co.id GROUP BY co.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;

公司:

Companies table

company_config_key:

company_config_key table

company_config:

company_config table

结果(应设置公司1和2的二级颜色):

query result

1 个答案:

答案 0 :(得分:0)

事实证明我只需将内部if语句设置为NULL,然后将max语句包装在IFNULL中。

SET @sql = NULL;
SELECT 
    GROUP_CONCAT(DISTINCT
        CONCAT('IFNULL(MAX(IF(cc.company_config_key_id  = ', cck.id, ', cc.config_value, NULL)), \'', cck.default, '\') AS ',cck.company_config_key)
    ) INTO @sql
    FROM company_config cc
    LEFT JOIN company_config_key cck
    ON cck.id = cc.company_config_key_id;
SET @sql = CONCAT('SELECT co.id, co.name, ', @sql, ' FROM companies co LEFT JOIN company_config cc ON cc.company_id = co.id GROUP BY co.id');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;