根据表中的不同值查询列

时间:2013-10-13 02:14:36

标签: php mysql sql dynamic

我有一个包含3个列的表。 Location_ID,Product_ID和Qty:

LOCATION_ID |   PRODUCT_ID    |  QTY
--------------------------------
1                   1              1
2                   1              3
1                   3              5
2                   3              2
2                   4              2
1                   4              5

每次将产品带入或带出某个位置时,都会在此表中创建或更新一行。

是否可以根据表中的Location_ID数量来创建一个添加列的查询?

我希望结果是这样的:

PRODUCT_ID | 1 | 2 |
--------------------
    1        1   3
    3        5   2
    4        5   2 

如果稍后添加更多LOCATION_ID,则会在查询中找到名为location id(3)的新列。

1 个答案:

答案 0 :(得分:0)

您必须为此

使用动态SQL
SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
         CONCAT('SUM(CASE WHEN location_id = ', location_id,
                ' THEN qty END) `', location_id, '`'))
  INTO @sql
  FROM table1;

SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                     FROM table1 
                    GROUP BY product_id');

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

输出:

| PRODUCT_ID | 1 | 2 |
|------------|---|---|
|          1 | 1 | 3 |
|          3 | 5 | 2 |
|          4 | 5 | 2 |

这是 SQLFiddle 演示


为简化客户端上的操作,您始终可以将其包装到存储过程中

DELIMITER $$
CREATE PROCEDURE products_by_location()
BEGIN
  SET @sql = NULL;

  SELECT GROUP_CONCAT(DISTINCT
           CONCAT('SUM(CASE WHEN location_id = ', location_id,
                  ' THEN qty END) `', location_id, '`'))
    INTO @sql
    FROM table1;

  SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                       FROM table1 
                      GROUP BY product_id');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

并使用它

CALL products_by_location();

这是 SQLFiddle 演示