php - 将 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
解决方案
如果您想在 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
推荐阅读
- angular - 模拟 http => 在 Angular 7 中返回 observable 的问题
- google-apps-script - 我可以根据另一个匹配的单元格条件使用 Google Apps 脚本自动链接两个单元格吗?
- database - 如何加快大型数据库中的 LIMIT & OFFSET 查询
- android - 如何在提交的所有时间显示验证码挑战对话框
- android - 根据 BuildTypes 选择风格
- python - Python无法解析变量,鸭子打字说?
- c# - 将选项值从一个下拉列表复制到另一个
- python - 计算 DataFrame 列表的平均值和众数
- c# - sqLite dotnet reader读取错误的int类型
- python-3.x - 如何获取 sqlite 查询的状态?