如何在一个表中链接两个表与自动增量ID?

时间:2011-04-13 01:59:55

标签: php mysql

如果我有这样的表

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

和另一张表

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

当需要将值插入表tbl_attributes时,因为我插入col1和col2的值,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格式,但我是那个世界的新手,事情可能搞砸了。

2 个答案:

答案 0 :(得分:2)

插入第一个自动增量表后,调用php函数mysql_insert_id()。这将返回上一个插入的自动增量ID,您可以在后续插入中使用它。 PHP函数调用的本机MySQL函数是LAST_INSERT_ID()

$result = mysql_query("INSERT INTO tbl_attributes (col1, col2) VALUES ('val1', 'val2');");

if ($result)
{
   // Get the auto increment id from the first INSERT
   $last_id = mysql_insert_id();
   // And use it in the second INSERT
   $result2 = mysql_query("INSERT INTO tbl_weight (id_attrib, field) VALUES ($last_id, 'fieldval');");
}
else // first insert failed
mysql_insert_id()

上的

Official PHP documentation

答案 1 :(得分:2)

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

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

手动:mysql_insert_id()

  

检索为其生成的ID   AUTO_INCREMENT列由前一个   查询(通常是INSERT)。

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

示例:

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

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