透视表仅返回1行

时间:2013-11-05 01:17:45

标签: mysql pivot dynamic-sql

我的SQLFiddle:http://sqlfiddle.com/#!2/729a9/1

正如您所看到的,尽管表中有两行,但仍有一行返回。

它也是最高的ID,所以也许这与它有关?

我很难说是一根木头,很遗憾地说。

SQL:

SELECT GROUP_CONCAT(distinct
             CONCAT(
              'max(case when `pat`.`name` = ''',
               `pat`.name,
               ''' then `pa`.`value` end) as `',
               `pat`.name, '`'
              )
            ) INTO @list 
FROM `product_attribute_types` pat;

SET @sql = CONCAT('select ', @list, ' 
                  from `products`  `p` 
                  LEFT JOIN `product_attributes` `pa` 
                    ON `p`.id=`pa`.`product_id`
                  LEFT JOIN `product_attribute_types` `pat`
                        ON `pa`.`type`=`pat`.`id`
                  ');

PREPARE stmt FROM @sql;
EXECUTE stmt;

2 个答案:

答案 0 :(得分:2)

首先:您有相同product_id = 1的两个属性,以这种方式更改表product_attributes -

INSERT INTO `product_attributes` (`product_id`,`type`,`value`) VALUES
  (1,1,'blue'),
  (1,2,'shirt'),
  (2,1,'green'),
  (2,2,'pants');

然后尝试这个 -

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pat.name = ''', name, ''', pa.value, NULL)) AS ', name
    )
  ) INTO @sql
FROM product_attribute_types;

SET @sql = CONCAT('SELECT pa.product_id, ', @sql, ' FROM product_attributes pa INNER JOIN product_attribute_types pat ON pa.type = pat.id GROUP BY pa.product_id');

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

结果:

+------------+-------+-------+
| product_id | color | name  |
+------------+-------+-------+
|          1 | blue  | shirt |
|          2 | green | pants |
+------------+-------+-------+

如果需要,添加WHERE过滤器。

答案 1 :(得分:1)

您在@sql中缺少GROUP BY子句,以及该行引用的产品ID。

SET @sql = CONCAT('select p.id, ', @list, ' 
                  from `products`  `p` 
                  LEFT JOIN `product_attributes` `pa` 
                    ON `p`.id=`pa`.`product_id`
                  LEFT JOIN `product_attribute_types` `pat`
                        ON `pa`.`type`=`pat`.`id`
                  GROUP BY p.id
                  ');

FIDDLE