0

I have two tables:

create table `db_csms`.`tbl_item_requester`
(
    `id` int not null,
    `item_id` int not null,
    `requester_id` int not null,
    foreign key(`item_id`) references `db_csms`.`tbl_items`(`item_id`),
    foreign key(`requester_id`) references `db_csms`.`tbl_user_details`(`user_id`),
    primary key (`id`)
);
create table `db_csms`.`tbl_item_requests`
(
    `id` int not null,
    `item_requester_id` int not null,
    `quantity` int(5) not null default 0,
    foreign key(`item_requester_id`) references `db_csms`.`tbl_item_requester`(`id`),
    primary key (`id`)
);

tbl_items and tbl_user_details are already populated with values. My problem is when a new row is added into table 1 because the table 2 uses the id of that new row inserted in table 1.

My issues are:

  1. How to get the newly inserted row id of table 1 which is needed for inserting in table 2.

Strategy to solve this issue(my thinking):

  1. Remove auto_increment and then generate a random value (using C# code) and use that value in both tables.

Are there any workaround to this problem? Do i have to change my strategy? Is the Database design incorrect?

5
  • 1
    Use last_insert_id(): dev.mysql.com/doc/refman/5.7/en/…. Commented Apr 6, 2015 at 12:07
  • @GordonLinoff does that return the correct id for multiple inserts from different clients Commented Apr 6, 2015 at 12:11
  • You have C# as a tag. How are you inserting records? SqlCommand? Linq-to-Sql? EF? Please show your c# code. ORMs provide the auto-generated id automatically. Commented Apr 6, 2015 at 12:17
  • Your question is specifically in the singular: "How to get the newly inserted row id". However, if you have multiple ids inserted in a single statement, they should be consecutive. Commented Apr 6, 2015 at 12:17
  • @Delphi.Boy MySqlCommand Commented Apr 6, 2015 at 12:25

2 Answers 2

1

Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID() which only works on the current connection that did the insert.

Sign up to request clarification or add additional context in comments.

Comments

1

In case of SQL Server you could write:

Insert .... Values(....); Select Scope_Identity()

and use SqlCommand.ExecuteScalar() that returns the first value of the first row, which would be the ID of newly inserted row. In MySql, you should be able to write last_insert_id() instead of Scope_identity().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.