[英]MySQL Bulk Insert Dependent on Another Table
I have a case where I'm doing two queries: query1
is a bulk INSERT ... ON DUPLICATE KEY UPDATE
on table1
. 我有一个情况,我在做两个查询: query1
是对table1
的批量INSERT ... ON DUPLICATE KEY UPDATE
。 For query2
, I want to do another bulk INSERT
on table2
with some application data along with using the ids inserted/updated from query1
. 对于query2
,我想对table2
进行另一个批量INSERT
,其中包含一些应用程序数据以及使用从query1
插入/更新的ID。 I know I can do this with an intermediate query, selecting the ids I need from table1
and then inserting them into table2
along with application data, but I really want to avoid the extra network back-and-forth of that query along with the db overhead. 我知道我可以使用中间查询来做到这一点,从table1
选择所需的id,然后将它们与应用程序数据一起插入到table2
,但是我真的想避免该查询与数据库一起往返网络高架。 Is there any way I can either get the ids inserted/updated from query1
when running that, or do some kind of complex, but relatively less expensive INSERT ... SELECT FROM
in query2
to avoid this? 有什么办法可以让我从运行时从query1
插入/更新的ID,或者执行某种复杂但相对便宜的INSERT ... SELECT FROM
在query2
中避免这种情况?
As far as I know, getting ids added/modified returned from query1
is impossible without a separate query, and I can't think of a way to batch INSERT ... SELECT FROM
where the insertion values for each row are dependent on the selected value, but I'd love to be proven wrong, or shown a way around either of those. 据我所知,没有单独的查询就不可能从query1
返回添加的ID或修改的ID,并且我无法想到一种批处理INSERT ... SELECT FROM
,其中每行的插入值取决于所选的值,但我希望证明自己是错的,或者显示出解决任何一种错误的方法。
There is no way to get a set of IDs as a result of a bulk INSERT
. 由于批量INSERT
无法获得一组ID。
One option you have is indeed to run a SELECT
query to get the IDs and use them in the second bulk INSERT
. 您确实可以SELECT
一种方法是运行SELECT
查询以获取ID并在第二个批量INSERT
使用它们。 But that's a hassle. 但这很麻烦。
Another option is to run the 2nd bulk INSERT
into a temporary table, let's call it table3
, then use INSERT INTO table2 ... SELECT FROM ... table1 JOIN table3 ...
另一个选择是将第二个批量INSERT
运行到临时表中,我们将其称为table3
,然后使用INSERT INTO table2 ... SELECT FROM ... table1 JOIN table3 ...
With a similar use case we eventually found that this is the fastest option, given that you index table3
correctly. 在类似的用例中,如果您正确索引table3
,我们最终发现这是最快的选择。 Note that in this case you don't have a SELECT
that you need to loop over in your code, which is nice. 请注意,在这种情况下,您没有需要在代码中循环的SELECT
,这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.