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

9rbhqvlz  于 2023-01-16  发布在  Mysql
关注(0)|答案(1)|浏览(257)

我有一个用MySQL编写的存储过程,我想把它的结果存储在一个临时表中。

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;

它目前正在工作,但当我从部件CREATE TEMPORARY TABLE required_items AS中删除注解时,它引发了错误。
我认为问题出在WITH的使用上,但是我在网上找不到任何类似的案例。
我将感谢您的建议和意见,谢谢!
附言:生成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);
kgsdhlau

kgsdhlau1#

错误消息指出SELECT DISTINCT component_id, SUM(bom_multiplier)*parent_item_count的列名不正确。当我将AS required_amount附加到该行时,问题得到了解决。

相关问题