MySQL存储过程或动态视图

时间:2014-04-30 13:24:06

标签: mysql excel stored-procedures views prepared-statement

我有以下准备好的语句来跨三个表运行动态数据透视查询

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT(
    'max(case when division_id = ', dp.division_id, ' then process_name end) AS ', d.division_shortName, ' '
    )
) INTO @sql
FROM 
    erp_divisionProcess dp LEFT JOIN erp_division d ON d.division_id = dp.division_id;
SET @sql = concat('SELECT ', @sql, 'FROM (
    SELECT d.division_id, p.process_name, X.rnk
    FROM erp_division d
    LEFT JOIN (SELECT dp.division_id, dp.process_id, (SELECT COUNT(*) FROM erp_divisionProcess A WHERE dp.division_id = A.division_id AND dp.process_id < A.process_id) AS rnk
    FROM erp_divisionProcess dp) X ON X.division_id = d.division_id
    LEFT JOIN erp_BusinessProcess p ON p.process_id = X.process_id 
) x
GROUP BY rnk');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

生成一个像这样的透视数据集:

+-----------------+-----------------+------------+------------+--------------+------------+------------+-------+
| PBL             | PLI             | PMI        | PBT        | PBP          | PBI        | PBTL       | PRDT  |
+-----------------+-----------------+------------+------------+--------------+------------+------------+-------+
| Sales           | Human Resources | Production | Purchasing | Sales        | Purchasing | Purchasing | Sales |
| Human Resources | Purchasing      | NULL       | NULL       | Purchasing   | NULL       | NULL       | NULL  |
| Purchasing      | Finance         | NULL       | NULL       | Distribution | NULL       | NULL       | NULL  |
| Distribution    | NULL            | NULL       | NULL       | Production   | NULL       | NULL       | NULL  |
| Production      | NULL            | NULL       | NULL       | NULL         | NULL       | NULL       | NULL  |
| Finance         | NULL            | NULL       | NULL       | NULL         | NULL       | NULL       | NULL  |
+-----------------+-----------------+------------+------------+--------------+------------+------------+-------+

我希望结果数据集可用于拉入Excel,但是当我尝试运行完整语句时,MS Query会抛出并出错。我相信我无法从准备好的语句中创建一个视图,所以如何在不必每次都重新键入(复制和粘贴)它并从MySQL获得结果的情况下获得查询结果。

谢谢!

1 个答案:

答案 0 :(得分:0)

  

我相信我无法从预备语句中创建视图,因此如何在不重新键入(复制和粘贴)的情况下获得查询结果

您可以使用准备好的查询创建view

尝试在代码中进行以下更改:

-- SET @sql = concat('SELECT ', @sql, 'FROM (
SET @sql = concat( 'CREATE VIEW view_name AS SELECT ', @sql, ' FROM (
    SELECT d.division_id, p.process_name, X.rnk
    FROM erp_division d
    LEFT JOIN (SELECT dp.division_id, dp.process_id, 
                      (SELECT COUNT(*) FROM erp_divisionProcess A 
                        WHERE dp.division_id = A.division_id 
                          AND dp.process_id < A.process_id) AS rnk
                 FROM erp_divisionProcess dp) X 
           ON X.division_id = d.division_id
    LEFT JOIN erp_BusinessProcess p ON p.process_id = X.process_id 
) Y
GROUP BY rnk');

创建视图后,您可以发出select * from view_name以将数据提取到客户端。

演示 @ MySQL 5.5.32 Fiddle