在两个相关表MySQL中插入值

时间:2015-04-06 12:06:01

标签: c# mysql

我有两张桌子:

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_itemstbl_user_details已填充了值。我的问题是当一个新行被添加到表1中时,因为表2使用了表1中插入的​​新行的id。

我的问题是:

  1. 如何获取插入table 1所需的table 2新插入的行ID。
  2. 解决这个问题的策略(我的想法):

    1. 删除auto_increment然后生成一个随机值(使用C#代码)并在两个表中使用该值。
    2. 这个问题有解决方法吗?我必须改变策略吗?数据库设计不正确吗?

2 个答案:

答案 0 :(得分:1)

由于您使用MySQL作为数据库,因此具有特定功能LAST_INSERT_ID() 它仅适用于执行插入的当前连接。

答案 1 :(得分:1)

如果是SQL Server,您可以写:

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

并使用SqlCommand.ExecuteScalar()返回第一行的第一个值,即新插入的行的ID。在MySql中,您应该能够编写last_insert_id()而不是Scope_identity()