我有两张桌子:
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
所需的table 2
新插入的行ID。解决这个问题的策略(我的想法):
这个问题有解决方法吗?我必须改变策略吗?数据库设计不正确吗?
答案 0 :(得分:1)
由于您使用MySQL作为数据库,因此具有特定功能LAST_INSERT_ID()
它仅适用于执行插入的当前连接。
答案 1 :(得分:1)
如果是SQL Server,您可以写:
Insert .... Values(....); Select Scope_Identity()
并使用SqlCommand.ExecuteScalar()
返回第一行的第一个值,即新插入的行的ID。在MySql中,您应该能够编写last_insert_id()
而不是Scope_identity()
。