Reputation: 2047
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:
table 1
which is needed for inserting in table 2
.Strategy to solve this issue(my thinking):
Are there any workaround to this problem? Do i have to change my strategy? Is the Database design incorrect?
Upvotes: 0
Views: 47
Reputation: 1216
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()
.
Upvotes: 1
Reputation: 692
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.
Upvotes: 1