我正在实施一种请求机制,用户必须批准请求。为此我已经实现了临时表和主表。最初在添加请求时,数据将被插入到临时表中,在批准时它将被复制到主表中。
问题是,批准后将有超过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
中粘贴了查询答案 0 :(得分:2)
对不起,我不熟悉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个字段。
希望得到这个帮助,
答案 1 :(得分:0)
只需更新您的架构即可。您应该拥有主表中的所有数据,而不是拥有两个表:一个main
和一个temporary
,而是有一个标志,指示某个记录是否被批准。最初它将设置为false,一旦批准,它将被设置为true,然后数据可以显示在您的网站上等。这样您就不需要write
数据两次,甚至必须将它从一个表移到另一个表
答案 2 :(得分:0)
你还没有指定你正在使用的RDBMS,但是使用SELECT的旧INSERT必须在一个命令中完成这个技巧:
insert main (field1,...,fieldN) select field1,...,fieldN from temporary