首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在两个相关表中插入值MySQL

在两个相关表中插入值MySQL
EN

Stack Overflow用户
提问于 2015-04-06 12:06:00
回答 2查看 40关注 0票数 0

我有两张桌子:

代码语言:javascript
复制
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中插入所需的新插入的行id。

解决这个问题的策略(我的想法):

  1. 删除auto_increment,然后生成一个随机值(使用C#代码),并在两个表中使用该值。

这个问题有什么解决办法吗?我必须改变我的策略吗?数据库设计不正确吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-06 12:13:19

因为您使用MySQL作为数据库,所以有特定的函数LAST_INSERT_ID(),它只在执行插入的当前连接上工作。

票数 1
EN

Stack Overflow用户

发布于 2015-04-06 12:33:55

如果使用SQL Server,您可以编写:

代码语言:javascript
复制
Insert .... Values(....); Select Scope_Identity()

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29470970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档