将一个表中自动生成的索引插入到另一个表中 [英] Inserting an automatically generated index from a table into another table

查看:59
本文介绍了将一个表中自动生成的索引插入到另一个表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个表:

  • table1 (id, name, type) 其中 id 为主键,自增
  • table2 (item_id, place) 其中 item_id 指的是 table1
  • 中的 id
  • table1 (id, name, type) where id is a primary key, and auto-incremented
  • table2 (item_id, place) where item_id refers to id in table1

我想做以下事情:

insert into table1(name, type) values (y, z);

假设该查询将为该行分配 id=x,则:

Assuming that that query would assign id=x for that row, then:

insert into table2(item_id, place) values (x, w);

我怎么能这样做?换句话说,我如何获得刚刚添加的行的 id ?

How could I do that? In other words, how could I get the id of the row that has just been added?

推荐答案

insert into table1(name, type) values (y, z);
insert into table2(item_id, place) values (LAST_INSERT_ID() , w);

LAST_INSERT_ID() 会为你做这件事.大多数编程语言都有一个特殊的函数来为你调用它,但它在纯 MySQL 中工作.

The LAST_INSERT_ID() will do this for you. Most programming languages have a special function that call this for you, but it works in pure MySQL.

这篇关于将一个表中自动生成的索引插入到另一个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆