首页 > 解决方案 > 将 foreach ID 插入其他表

问题描述

我试过寻找我想要的东西,但我仍然对代码感到困惑。我的问题是这样的:

我有 3 张桌子

 1. table1 (post id, field2, ...) ex. (1, ...)
 2. table2 (tag id, tag) ex. ("1, ...", "2, ...")
 3. table3 (post id, tag id) ex. ("1, 1", "1, 2")

那么如何在 table3 中输入值 post id 和 tag id 呢?

PHP代码:

  foreach($tags as $tag){
    $query_insert_tags = mysql_query("INSERT INTO tb_tags (tag) VALUES ('$tag')") or die(mysql_error());
    $query_insert_tag_posts = mysql_query("...") or die(mysql_error());
  }

像这样:

insert into table3 (post id, tag id) 
select post id from table1 and select tag id from table2

不知道是不是这样,我也不知道怎么把值放到数据库里

INSERT INTO table3 (post_id, tag_id)
SELECT table1.postid, table2.tagid FROM table3
JOIN table1 ON table3.postid = table1.postid
JOIN table2 ON table3.tagid = table2.tagid

标签: phpmysql

解决方案


如果您想在 MySQL 级别上执行此操作,则必须在其中一个表上有一列连接 table1 和 table2。

在没有该列的情况下执行此操作的最佳方法是在插入表 1 和 2 时保留最后一个插入 ID,而不是将这些 ID 插入表 3:

$mysqli->query("INSERT INTO table1 ...");
$lastPostId = $mysqli->insert_id;
$mysqli->query("INSERT INTO table2 ...");
$lastTagId = $mysqli->insert_id;
$mysqli->query("INSERT INTON table 3 (post_id, tag_id) VALUES ({$lastPostId}, {$lastTadId})");

如果您只想将所有可能的 post_id 和 tag_id 插入到表 3 中,您可以执行以下操作:

INSERT INTO table3 (post_id, tag_id)
SELECT post_id, tag_id
FROM table1
JOIN table2 ON 1=1

推荐阅读