简体   繁体   English

如何使用带有外键的anorm批量插入两个表

[英]How to batch insert to two tables using anorm with foreign key

Im having trouble doing this batch operations like this. 我在执行这样的批处理操作时遇到了麻烦。

val params = Seq(Seq[NamedParameter]("valueA" -> 1, "valueB" -> 2))

BatchSql(SQL(
  """
     INSERT INTO tableA ( valueA ) VALUES ( {valueA} );
     INSERT INTO tableB ( tableAId, valueB ) VALUES ( LAST_INSERT_ID(), {valueB});
  """.stripMargin), params).execute()

With tables like... 像这样的桌子

CREATE TABLE tableA
(
  id int AUTO_INCREMENT PRIMARY KEY,
  valueA int
); 

CREATE TABLE tableB
(
  id int AUTO_INCREMENT PRIMARY KEY
  tableAId int,
  valueA int,
  FOREIGN KEY (tableAId) REFERENCES tableA (id),
); 

I get this exception, just complaining about line 2. 我收到这个例外,只是抱怨第二行。

BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO tableB  ( tableAid, valueA' at line 1]]

Thanks 谢谢

You need two tables, the first generates the primary key, the second uses the newly created primary key as foreign key .. 您需要两个表,第一个表生成主键,第二个表使用新创建的主键作为外键..

create table TABLE_1 columns ID_TABLE_1 PK, A, B (UNIC), C;
create table TABLE_2 columns ID_TABLE_1 FK, D, E;

DECLARE @unicValue int = 987;
INSERT INTO TABLE_1 (A,B,C) VALUES ('A', @unicValue, 'C');

INSERT INTO TABLE_2 (ID_TABLE_1, D, E) VALUES (
 (SELECT ID_TABLE_1 FROM TABLE_1 WHERE B = @unicValue), 'VALUE', 'C');
  • Add multiple "batch".. 添加多个“批”。
  • Execute batch ! 执行批处理!

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

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