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

标签 mysql sql

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

我现在拥有的: 从 [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/

相关文章:

jquery - 多雇主对员工管理

mysql - Drupal 站点缓慢,Drupal 调整

mysql - 为多对多关系插入多个值时如何避免重复 - mysql

PHP/SQL : Leveling/XP System for users on a website. 我应该如何存储数据?关于 session 的思考

sql - 创建具有多个表的动态 View

php 日期和 mysql 时间戳比较

mysql - 我有一个选择查询,结果是我得到一个列。现在我需要将所有这些列值以 CSV 格式

mysql - 在一个列和其他所有内容上选择不同

sql - 按输入时对 Access 中的字段进行排序

java - 如何使用java代码在单个数据库中一次连接多个模式