简体   繁体   English

在包含“WITH”的存储过程中创建临时表[MySQL]

[英]Create Temporary Table in a Stored Procedure Including "WITH" [MySQL]

I have a stored procedure written in MySQL, and I want to store its results in a temporary table.我有一个存储过程写在 MySQL 中,我想将它的结果存储在一个临时表中。 Here is the code:这是代码:

DELIMITER $$
CREATE PROCEDURE GetRequiredItemsCount(
    IN item VARCHAR(16),
    IN parent_item_count INT)

    BEGIN
/*      DROP TABLE IF EXISTS required_items;
        CREATE TEMPORARY TABLE required_items AS */
        
            WITH RECURSIVE bom_temp AS (

                SELECT bom.item_id, bom.component_id, bom.bom_multiplier
                FROM bom
                WHERE bom.item_id = item
                
                UNION ALL

                SELECT child.item_id, child.component_id, child.bom_multiplier
                FROM bom_temp parent
                    JOIN bom child ON parent.component_id = child.item_id
                )

            SELECT DISTINCT component_id, SUM(bom_multiplier)*parent_item_count
            FROM bom_temp
            GROUP BY component_id;
    END$$
DELIMITER;

It is currently working, but when I remove the comments from the part CREATE TEMPORARY TABLE required_items AS , it raises error.它目前正在工作,但是当我从CREATE TEMPORARY TABLE required_items AS部分中删除注释时,它会引发错误。

I think the problem is the use of WITH , but I could not find any similar cases on the.net.我认为问题出在WITH的使用上,但我在 .net 上找不到任何类似的案例。

I would appreciate your suggestions and comments, thanks!非常感谢您的建议和意见,谢谢!

PS: "bom" table is generated as follows: PS:“bom”表生成如下:

CREATE TABLE bom (  item_id VARCHAR(16),
                    component_id VARCHAR(16),
                    bom_multiplier INT NOT NULL,
                    PRIMARY KEY (item_id, component_id));

INSERT INTO bom (item_id, component_id, bom_multiplier)
VALUES  ("001", "002", 1),
        ("001", "003", 1),
        ("002", "004", 3),
        ("002", "005", 3); 

The error message was pointing out the incorrect column name for SELECT DISTINCT component_id, SUM(bom_multiplier)*parent_item_count .错误消息指出SELECT DISTINCT component_id, SUM(bom_multiplier)*parent_item_count的列名称不正确。 The problem was solved when I appended AS required_amount to that line.当我将AS required_amount附加到该行时,问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM