Nan*_*r V 5 php sql postgresql
我正在实现一个请求机制,用户必须批准请求.为此我已经实现了临时表和主表.最初在添加请求时,数据将被插入到临时表中,在批准后它将被复制到主表中.
问题是,批准后将有超过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
Run Code Online (Sandbox Code Playgroud)
但是这个实现将至少需要20k个查询.有没有更好的方法来实现相同的.
我试图创建一个sqlfiddle但无法创建一个.所以我在pgsql.privatepaste.com中粘贴了查询
抱歉,我对 PostgreSQL 不熟悉。我的解决方案是在 MySQL 中,我希望它能有所帮助,因为如果它们(MySQL 和 PostgreSQL)相同。
首先,我们应该在您的batch_main表中再添加1个字段来跟踪每个batch_main记录的原始batch_temp记录。
ALTER TABLE `batch_main`
ADD COLUMN tempid bigint;
Run Code Online (Sandbox Code Playgroud)
然后,在批准后,我们将通过 1 个查询插入 5k 行:
INSERT INTO batch_main
(batchid, userid, amount, tempid)
SELECT batchid, userid, amount, amount_id FROM batch_temp;
Run Code Online (Sandbox Code Playgroud)
因此,对于每个新的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
Run Code Online (Sandbox Code Playgroud)
完毕!
P/S:我对你命名字段的方式有点困惑,因为我不了解 PostgreSQL,通过研究你的语法,你可以对表batch_temp和batch_main的主键使用相同的序列吗?如果可以的话,就不需要再添加 1 个字段。
希望这有帮助,
归档时间: |
|
查看次数: |
189 次 |
最近记录: |