简体   繁体   English

使用自动增量MySQL将多行插入两个表

[英]Insert multiple rows into two tables using autoincrement Mysql

I am trying to insert multiple rows into two tables connected by a foreign key that is autoincrement. 我试图将多个行插入通过自动增量外键连接的两个表中。 I can't seem to find a good solution. 我似乎找不到一个好的解决方案。 Tables: 表:

  • eav_attribute_option eav_attribute_option

    • option_id (PK, Autoincrement) option_id(PK,自动递增)
    • attribute_id attribute_id
    • sort_order 排序
  • eav_attribute_option_value eav_attribute_option_value

    • value_id (PK, Autoincrement) value_id(PK,自动递增)
    • option_id (FK) option_id(FK)
    • store_id STORE_ID
    • value

I want to do this: 我想做这个:

insert into eav_attribute_option(attribute_id) values(100,101,102,103,...);
insert into eav_attribute_option_value(option_id,store_id,value) values 
    (1,0,"English"),(1,1,"German"),(2,0,"English1"),(2,1,"German2")

What would be the best approach to this, I can't seem to find a good one. 最好的方法是什么,我似乎找不到一个好的方法。 :

  • Get next autoincrement then insert with it (need to lock table between) 获取下一个自动增量,然后插入它(需要锁定它们之间的表)
  • Insert first part, then retreive PK values, build second part and insert (data incomplete for some time, what happens on error in second part?) 插入第一部分,然后获取PK值,构建第二部分并插入(数据一段时间不完整,第二部分中的错误会发生什么?)
  • Some way to insert with join if it's possible? 如果可能的话,可以使用join插入的某种方式?

Edit: Just to clarify, I am looking to use the least amount of queries possible. 编辑:只是为了澄清,我正在寻找使用尽可能少的查询。 I know I can do last inserted id, but I don't want to kill the server with thousands of inserts. 我知道我可以做最后插入的id,但是我不想杀死具有数千个插入的服务器。

You can try something like this: 您可以尝试如下操作:

insert into eav_attribute_option (attribute_id) values(100);

insert into eav_attribute_option_value (option_id, store_id, value)
values (LAST_INSERT_ID(), 0, "English");

But you will need to insert the rows one by one. 但是您将需要一行一行地插入行。 Consider doing a loop in your application. 考虑在您的应用程序中进行循环。

$count = count('Count post value'); // $_POST value count

for($a=0;$a<$count;$a++)
{
    $insert = 'insert into eav_attribute_option(attribute_id,sort_order) values (value1,value2)';
    mysql_query($insert);
    $insert_id = mysql_insert_id();

    $insert2 = 'insert into eav_attribute_option_value(option_id,store_id,value) values 
                ($insert_id,0,"English")';
    mysql_query($insert2);
}

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

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