繁体   English   中英

从另一个表更新一个表

[英]Updating one table from another table

我创建了一个新表供我使用,可以说t1其中有8列。 我已通过一个过程填充了3列。 第1列是名称。 现在,我想在第四栏中填充相应的名称。 这将通过where子句进行更新。

场景是我创建了一个查询结果的查询,调用了具有名称和total_amount的t2。 现在,我想将total_amount填充到t1的第四列中。

我现在要遵循的方法是遍历t1中的每个名称,并在t2(with子句)中找到其计数器total_amount,然后在t1中更新值。 但这需要无限的时间。 首先是因为在t1中循环,第二是t2本身是一次又一次执行的查询。

现在,实际的任务要复杂得多,我只是提供了关键所在。 请给我建议一种快速的方法。

create or replace procedure proc
is

temp_value number(18,2);

CURSOR total is
select name, age, sex from data_table where
{conditions};

/*Gives me name and age in 1st and 2nd column and likewise data in 3rd column */

begin

FOR temp IN total LOOP

    with aa as (SELECT b.name,
         NVL (SUM (c.amount), 0) as total_amount
    FROM data_table2 b, data_table3 c
   WHERE     {joins and groub by}
   )
   /* This gives me total amount for corresponding name. There is no repetition of name */

   select nvl(sum(total_amount),0) into temp_value from aa where name = temp.name;

    update t1 set amount = temp_value where name = temp.name;

    END LOOP;

END;
/

无法在问题上添加评论,因此将其放在此处。

根据您的示例:

    with aa as (SELECT b.name,
     NVL (SUM (c.amount), 0) as total_amount
FROM data_table2 b, data_table3 c
WHERE     {joins and groub by}
)
/* This gives me total amount for corresponding name. There is no repetition of name */

select nvl(sum(total_amount),0) into temp_value from aa where name = temp.name;

update t1 set amount = temp_value where name = temp.name;

在with子句中,您求和,然后为光标中的所有名称填充这些总和。 为什么您不能直接这样做:

    SELECT SUM(NVL(total_amount, 0)) INTO temp_vale FROM
       data_tabl1, data_tabl2, data_tabl3
       WHERE
        --JOIN CONDITIONS
      AND data_tabl1.total)name = --data_tabl2/3.name
    GROUP BY --clause;

我为什么这么说,with子句并不总是一个好主意。 如果您的“ with”有大量数据,那么它将永远运行。 “ With”用于处理重复表,并重复连接小数据。

同样出于调整目的,请尝试一些提示。

另外,NVL(SUM ..)为什么不求SUM(NVL(total_amount,0))?

暂无
暂无

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

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