我有两张桌子:
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和tbl_user_details已经填充了值。我的问题是,当一个新行被添加到表1中时,因为表2使用了表1中插入的新行的id。
我的问题是:
table 1中插入所需的新插入的行id。解决这个问题的策略(我的想法):
这个问题有什么解决办法吗?我必须改变我的策略吗?数据库设计不正确吗?
发布于 2015-04-06 12:13:19
因为您使用MySQL作为数据库,所以有特定的函数LAST_INSERT_ID(),它只在执行插入的当前连接上工作。
发布于 2015-04-06 12:33:55
如果使用SQL Server,您可以编写:
Insert .... Values(....); Select Scope_Identity()并使用SqlCommand.ExecuteScalar()返回第一行的第一个值,这将是新插入的行的ID。在MySql中,您应该能够编写last_insert_id()而不是Scope_identity()。
https://stackoverflow.com/questions/29470970
复制相似问题