且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

引用自增列?

更新时间:2023-02-03 08:03:10

您需要在依赖表中创建一个名为parent_id"的 INT 列,该列存储它所引用的主表的 ID.当您从第一个选择记录时,您将使用第一个字段的 auto_increment 字段对第二个字段的parent_id"加入表.

You need to create an INT column called something like "parent_id" in the dependant tables that stores the id of the main table that it is referencing. When you select records from the first, you would then JOIN the tables with the auto_increment field of the first field against the "parent_id" of the second.

正如 MrSlayer 提到的,使用第一张表的新插入的 ID 来更新parent_id".您应该通常在第二个表中有一个唯一的 ID 字段以确保唯一性,但它不应该是与第一个表的关系的一部分.

As MrSlayer mentions, use the newly inserted ID of the first table to update "parent_id". You should typically have a unique ID field in the second table for uniqueness, but it shouldn't be part of the relationship to the first table.

如果您不清楚如何获取插入时第一个表自动递增的 id,请使用 mysql_insert_id().

If you're unclear about how to get the id that the first table auto_increments to when you insert, use mysql_insert_id().

mysql_query("INSERT INTO table1 ...");
echo "Last inserted record_id in table1 was " .  mysql_insert_id();

INSERT INTO table1 (mytextcolumn) VALUES('text');
INSERT INTO table2 (parent_id,image_name) VALUES(LAST_INSERT_ID(),'someimage.png');