PHP-SQL如何从表中选择ID并插入到另一个表中?

问题描述:

我需要使用insert into语句进行内部联接.我需要将数据插入2个表中,但第二个表中记录的ID也应存储在第一个表中的列中.

I need to do an inner join with the insert into statement. I need to insert data into 2 tables but the id of the records from the second table should also be stored into a column from the first table.

第一个sql部分为dj表中的每个给定dj名称创建一个新记录,第二个部分应该从添加的dj中获取ID,并将其插入到"articles"表中的列中.

the first sql section makes a new record for every given dj name in the dj table, the second part is supposed to get the id from the added dj and insert it into a column from table "articles".

$alle_djs = explode(', ', $this->djs);
foreach ($alle_djs as $elke_dj) {
  $sql = "INSERT INTO dj (name) VALUES ( :name_dj )";
  $st = $conn->prepare($sql);
  $st->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
  $st->execute();

  $sql2 = "INSERT INTO articles (dj_ids) SELECT id FROM dj WHERE name=:name_dj";
  $st2 = $conn->prepare($sql2);
  $st2->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
  $st2->execute();
}
$conn = null

使用LAST_INSERT_ID()函数:

$sql2 = "INSERT INTO articles(dj_ids) VALUES (LAST_INSERT_ID())";