0

Structure:

Table A)

CREATE TABLE Item (
  Id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id of an item',
  `By` VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY (Id),
  CONSTRAINT FK_Item_User_Name FOREIGN KEY (`By`)
    REFERENCES User(Name) ON DELETE NO ACTION ON UPDATE CASCADE
)

Table B)

CREATE TABLE ItemName (
  Item_Id INT(11) UNSIGNED NOT NULL COMMENT 'Item id this name is referencing',
  Language VARCHAR(5) NOT NULL COMMENT 'language code by ISO 639-2/T',
  Translation VARCHAR(50) NOT NULL COMMENT 'Item name for given language',
  PRIMARY KEY (Item_Id, Language),
  CONSTRAINT FK_ItemName_Item_Id FOREIGN KEY (Item_Id)
    REFERENCES Item(Id) ON DELETE CASCADE ON UPDATE CASCADE
)

Table C)

CREATE TABLE User (
  Name VARCHAR(50) NOT NULL,
  Password VARCHAR(50) NOT NULL,
  Salt VARCHAR(255) NOT NULL,
  Blocked TINYINT(1) DEFAULT 0,
  PRIMARY KEY (Name),
  UNIQUE INDEX UK_User_Name (Name)
)

Question:

Now I want to insert a new item. Let's say the user provides us with:

  • Translation
  • Language code
  • Username

What i got so far:

I was thinking of puting it in a transaction and inserting into each table after eachother. But then i'm stuck on how do i know what Item.Id to use in the ItemName.Item_Id field since the Item table will AI a new Id for the insert.

I could get the last Item.Id, but then it might be pointing to another item if multiple users were to be inserting a new item simulaneuosly.

ps. Engine=InnoDB

Koen Demonie
  • 539
  • 1
  • 7
  • 24

1 Answers1

0
BEGIN;
INSERT into one table;
get the last_insert_id() -- there are many ways to do this, depending on the API
INSERT into next table...
... ;
COMMIT;

Do the inserts in the order that avoids violating your FOREIGN KEYs.

Rick James
  • 135,179
  • 13
  • 127
  • 222