Multiple ID SQL query


Multiple ID SQL query

假设我有两个表。

第一个:

id thing1 thing2

第二:

id_fo other_thing

其中id_fo取决于第一个表。

我必须在两个表中插入 thingS,但在 php mysql 请求(例如 pdo(中,我如何获取所有最后插入 id?

我的意思是,如果我在一个查询中有 30 行,我将有 30 个新 id。

如何进行第二次 SQL 查询?

在伪代码中:

Start transaction
  insert into table1 (thing1, thing2) values (thingS,thingS2)
  lastidtable1 = lastinsertedid();
  insert into table2 (id_fo, other_thing) values (lastidtable1,thingS);
  lastidtable2 = lastinsertedId();
commit;

以上每一行都应该php调用查询的代码。

你在寻找这样的东西吗?

   $main_data = array('dino', 'babu', 'john');
    foreach($main_data as $main) {
      // Insert main to 1st table
      mysql_query("MY INSERT QUERY TO TABLE 1");
      // Get the last insert id
      $new_id = mysql_insert_id();
      // Insert the sub data to 2nd table using the insert id
      mysql_query("MY INSERT QUERY TO TABLE 2 USING $new_id ");
    }
INSERT

和 UPDATE 不返回任何数据集,您可以添加时间戳类型的 INSERT 列,将 DEFAULT 设置为 CURRENT_TIMESTAMP 并选择所有时间戳值最大的行。

如果你能保证一次只有一个插入过程在进行,你可以做一些类似这样的伪代码:

$max1=select max(id) as max1 from table;
insert into table ....
$num_inserted_rows=number of inserted rows.
$max2=select max(id) as max2 from table;
if(($max2-$max1) == $num_inserted_rows){
    $lastid=select last_insert_id();
    $inserted_ids=range($lastid-$num_inserted_rows,$lastid);
}