【问题标题】:Issue in copying rows from one table to another将行从一个表复制到另一个表的问题
【发布时间】:2013-05-29 06:10:05
【问题描述】:

我正在实施一种请求机制,用户必须批准请求。为此,我实现了一个临时表和主表。最初,当请求被添加时,数据将被插入到临时表中,经批准后,它将被复制到主表中。

问题是批准后将有超过 5k 行移动到主表 + 明细表中的每行另外 3-5 行(存储详细信息)。 我现在的实现是这样的

//Get the rows from temporary table (batch_temp)
    //Loop through the data
        //Insert the data to the main table (batch_main) and return the id 
        //Get the details row from the temporary detail table (batch_temp_detail) using detail_tempid
            //Loop through the data
                //Insert the details to the detail table (batch_main_detail) with the main table id amount_id
            //End Loop  
    //End Loop

但这种实现至少需要 20k 次查询。有没有更好的方法来实现相同的。

我尝试创建一个 sqlfiddle,但无法创建一个。所以我把查询粘贴到pgsql.privatepaste.com

【问题讨论】:

  • 你试过select into吗?
  • 我没有尝试过SELECT INTO,但我已经阅读了文档。据我了解SELECT INTO 将返回无效。但是我需要batch_main中的amount_id来将相应的数据插入batch_main_detail。
  • 您是否有一个字段可以标记临时表和主表中记录的关系?如果你有,我想你可以用 2 个查询来完成你的任务,给我看看你的表结构。
  • @Tarzan 我已将链接附加到问题中的表结构。请检查一下。在该结构中batchid 是连接主表和临时表中的行的关系

标签: php sql postgresql


【解决方案1】:

对不起,我不熟悉 PostgreSQL。我的解决方案是在 MySQL 中,我希望它能有所帮助,因为如果它们(MySQL 和 PostgreSQL)是相同的。

首先,我们应该在您的 batch_main 表中再添加 1 个字段,以跟踪每个 batch_main 记录的原始 batch_temp 记录。

ALTER TABLE `batch_main`
    ADD COLUMN tempid bigint;

然后,在批准后,我们​​将通过 1 个查询插入 5k 行:

INSERT INTO batch_main
    (batchid, userid, amount, tempid)
    SELECT batchid, userid, amount, amount_id FROM batch_temp;

因此,对于每个新的 batch_main 记录,我们都有其原始 batch_temp 记录的 ID。然后,插入详细记录

INSERT INTO `batch_main_detail`
    (detail_amount, detail_mainid)
    SELECT
        btd.detail_amount, bm.amount_id
        FROM 
            batch_temp_detail `btd`
            INNER JOIN batch_main `bm` ON btd.detail_tempid = bm.tempid

完成!

P/S: 我对您命名字段的方式有点困惑,并且由于我不了解 PostgreSQL,并且通过查看您的语法,您能否对表 batch_temp 和 batch_main?可以的话就不用多加1个字段了。

希望对您有所帮助,

【讨论】:

    【解决方案2】:

    只需更新您的架构。与其拥有两张表:一张main 和一张temporary,您应该拥有主表中的所有数据,但有一个标志,表明某条记录是否被批准。最初它将被设置为 false,一旦获得批准,它将被简单地设置为 true,然后数据可以显示在您的网站等上。这样您就不需要 write 两次数据,甚至不必移动它从一张桌子到另一张桌子

    【讨论】:

    • 实际上我给出的表只是一个示例结构,两个表都包含比这更多的字段。
    • 计算也有一些复杂性。临时中的某些行不会复制到主表中...必须添加到另一个表中。
    【解决方案3】:

    您没有指定您正在使用的 RDBMS,但是带有 SELECT 的旧​​ INSERT 必须在一个命令中完成:

    insert main (field1,...,fieldN) select field1,...,fieldN from temporary
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多