php - 如何在一个表中链接两个具有自动递增 id 的表?

标签 php mysql

如果我有这样一张 table

tbl_attributes
---------------
id_attrib (auto incremented, primary key)
col1
col2

还有一张 table

tbl_weight
--------------
id_attrib *(not primary key)*
field

当我为 col1 和 col2 插入值时,需要将值插入表 tbl_attributes 时,id_attrib 会自动递增。我如何将 id_attribute 的相同自动增量值插入到表 tbl_weight 中的字段 id_attrib 中。我这样做的原因是因为 我正在寻找输入到 tbl_attributes 中的特定值,一旦我寻找的值已插入到 tbl_attributes 中,那么与此相关的更多信息将输入到 tbl_weight 中。

否则,如果我将表格组合起来会像

tbl_attributes
----------------
id_attrib
col1
col2
field (from tbl_weight table)

字段列将包含大量空数据,并且仅在满足某些条件时才包含数据,我不想那样做。

所以也许让当前的 auto_increment 用于 tbl_attributes 并插入该值。我正在考虑使用 innodb 格式,但我是那个世界的新手,事情可能会搞砸。

最佳答案

$sql = "INSERT INTO tbl_attributes VALUES(...)";
$res = mysql_query($sql);

if ($res) {
  $last_autoincrement_id = mysql_insert_id();
  // add code here
  }

手册:mysql_insert_id()

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

现在您可以将该 ID 用于另一个 INSERT 查询 (tbl_weight)。

例子:

$sql = "INSERT INTO tbl_weight VALUES('$last_autoincrement_id', ...)";
mysql_query($sql);

注意:不要忘记检查 mysql_query() 结果。

关于php - 如何在一个表中链接两个具有自动递增 id 的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643631/

相关文章:

php - 'field list' 中的未知列,在 db 中,在更改字段名称后

mysql - 如何并排显示结果

php - 向查询添加行的语法

mysql - 在 MYSQL 中添加日期和检查 NULL 值

php - 如何从现有登录 session 中调用 id?

mysql - MySQL 中的竞争条件 - 防止多次插入

php - 使用 GD 库编写印地语字体未按预期呈现

PHP:过滤和发布文本文件

php - 如何在 Drupal 中保存自定义模块中的复选框值?

javascript - 在表 JQuery 上搜索