如果我有这样一张 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
}
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/