gpt4 book ai didi

Mysql:将查询结果存储到单独的临时/虚拟表中

转载 作者:行者123 更新时间:2023-11-29 12:57:42 27 4
gpt4 key购买 nike

我想要的:我想在单独的查询中处理每一行结果。

我现在拥有的: 从 [QUERY] 中选择 field1、field2 INTO @field1、@field2

问题:如果[QUERY]返回多个结果,我将收到异常。

问题:[main]:如何将结果存储到表中?

问题:[sub]:如何对结果表的每一行执行单独的查询?

即:

SET result_table = SELECT field1, field2 INTO @field1, @field2 FROM [QUERY]
For each row of result_table do QUERY2

最佳答案

您考虑过使用光标吗?

DELIMITER $$
CREATE PROCEDURE sample_procedure
BEGIN
-- We need this variable to identify the end of our procedure
DECLARE finished_flag INTEGER DEFAULT 0;
-- These are variables for the fields you have, match the types.
DECLARE field1 varchar(100);
DECLARE field2 int;
DECLARE field3 datetime;

-- declare cursor for our select
DECLARE run_foreach_cursor CURSOR FOR
SELECT
field1,
field2
FROM [QUERY];

-- declare NOT FOUND so we know when we've run out of results
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished_flag = 1;

-- Open the cursor
OPEN run_foreach_cursor;

run_foreach_content: LOOP

-- Put fields list on this line, this is where they go.
FETCH run_foreach_cursor INTO field1, field2;

IF finished_flag = 1 THEN
LEAVE run_foreach_content;
END IF;

-- Do your query here.
INSERT INTO [tbl2]
VALUES
(
field1,
field2 + 7
);

-- Marks the end of our loop
END LOOP run_foreach_content;

-- Close the cursor so MySQL can free up the query attached to it.
CLOSE run_foreach_cursor;

END $$

DELIMITER ;

CALL sample_procedure();

关于Mysql:将查询结果存储到单独的临时/虚拟表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23787425/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com