简体   繁体   English

如何在一个表中插入相同的LAST_INSERT_ID()以创建多个记录;

[英]how to insert same LAST_INSERT_ID() in one table to create multiple records;

I am programming a website, with ASP.NET, C#, as well as using MYSQL. 我正在使用ASP.NET,C#和MYSQL对网站进行编程。 I need to be able to record two rows with same child_id; 我需要能够用相同的child_id记录两行;

My problem is with this one statement, it inserts one row and skips the last. 我的问题是与此一条语句,它插入一行并跳过最后一行。

   //data.ChldrenRecord.Service contain two records
   // babysit, and tutor
  foreach (string s in data.ChildrenRecord.Services)
  {
     query += (" INSERT INTO ServiceChildren SET service='" + s + "', child_id=LAST_INSERT_ID();");
  }

so table should look something like this 所以桌子应该看起来像这样

 id   service    child_id
 1    babysit    1
 2    tutor      1

I use Last_INSERT_ID() because child_id is a foreign key. 我使用Last_INSERT_ID(),因为child_id是外键。 I create a record in another table whose primary key is child_id. 我在另一个表中创建一条记录,该表的主键是child_id。 Afterwards, I use LAST_INSERT_ID() to reference that one record primary key child_id so that i may use it in my ServiceChildren table. 之后,我使用LAST_INSERT_ID()来引用该记录的主键child_id,以便可以在ServiceChildren表中使用它。

as it stands my table looks: 就我的桌子而言:

 id    service   child_id
 1     babysit   1

I think i am on the right track now. 我想我现在走在正确的轨道上。 if i log directly into the database, this statement works: 如果我直接登录数据库,则此语句有效:

  SET @last_id = LAST_INSERT_ID();
 //then insert statements
  INSERT INTO ServiceChildren(service, child_id) VALUES('babysit', @last_id);
  INSERT INTO ServiceChildren(service, child_id) VALUES('tutor', @last_id);

BUT IN MY C#, ASP.NET CODE THE LINE SET @last_id = LAST_INSERT_ID(); 但是在我的C#中,ASP.NET将行设置为@last_id = LAST_INSERT_ID(); does not do anything, even populate tables with a prior insert statement. 不会执行任何操作,甚至不会使用先前的insert语句填充表。

OK, I found out my problem. 好的,我发现了我的问题。 I needed to place Allow User Variables=True in the connection string to be allowed to create and use @last_id . 我需要在连接字符串中放置Allow User Variables = True ,以允许创建和使用@last_id

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

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