php - INSERT INTO,多个 WHERE IN,检查值是否存在
问题描述
我正在一个相对较长的多维数组中收集有关 30 个带有标题和内容的帖子的信息,然后通过一个 MySQL 查询将它们全部放入数据库中。但是我的检查查询与插入是分开的。我正在通过新帖子的标题检查类似的帖子,然后将其插入。如何将检查查询与插入查询合并?
这是我的多维数组,大约 30 个帖子:
array(
[0] => array(
[post_title] => $postTitle1,
[post_content] => $contentTitle1,
)
[1] => array(
[post_title] => $postTitle2,
[post_content] => $contentTitle2,
)
[N] => array(
[post_title] => $postTitleN,
[post_content] => $contentTitleN,
)
);
这是我对新帖子标题的检查查询(为每个帖子完成并且工作正常):
SELECT post_title FROM x_post WHERE post_title=$newPostTitle
这是我的插入查询(工作正常):
INSERT INTO x_post (`post_title`, `post_content`, `date_created`, `user_id`)
VALUES ((((( My multidimensional array's information will be here after processing )))))
最后这是我想要的查询,但它不起作用(合并两个查询):
INSERT INTO x_post (`post_title`, `post_content`, `date_created`, `user_id`)
SELECT * FROM (SELECT $postTitle1, $content1, $time, $userId") AS tmp1, (SELECT $postTitle2, $content2, $time, $userId") AS tmp2, .......... and so on ........... , (SELECT $postTitle30, $content30, $time, $userId") AS tmp30 WHERE NOT EXIST (SELECT x_post.post_title FROM x_post WHERE x_post.post_title IN ($newPostTitle1, $newPostTitle2, ... and so on... , $newPostTitleN))
编写查询的最佳方法是什么?事实上,我想检查所有 30 个帖子,如果在一个查询中存在相似,然后插入那些不相似的。我知道这很复杂,但会是一个很好的查询。
非常感谢。
解决方案
您可以使用UNION ALL
来制作一组您的个人FROM
-less SELECT
s,然后您可以将其用作一个派生表而不是 30 个。而不是IN
在WHERE
子句中使用,您可以直接关联。
INSERT INTO x_post
(`post_title`,
`post_content`,
`date_created`,
`user_id`)
SELECT `post_title`,
`post_content`,
`date_created`,
`user_id`
FROM (SELECT $postTitle1 `post_title`,
$content1 `post_content`,
$time `date_created`,
$userId `user_id`
UNION ALL
...
UNION ALL
SELECT $postTitle30 `post_title`,
$content30 `post_content`,
$time `date_created`,
$userId `user_id`) tmp
WHERE NOT EXISTS (SELECT *
FROM x_news
WHERE x_news.news_title = tmp.`post_title`);
推荐阅读
- swift - 在 Swift 中使用 DispatchQueue 循环 Alamofire 请求后如何获得通知?
- gatsby - 如何在 Gatsby 博客 Mdx 文件中导入图像(用于光滑的轮播)
- asp.net-core - 将 .NET 代码应用程序发布到 Arvixe Host
- python - 我的单词搜索生成器中仅使用了数组中的 1 个单词
- c++ - 防止 g++/clang++ 接受以大括号结尾的文件?
- python - Tkinter else 子句在按钮激活时在 if 语句之前执行
- workflow - Apache Airflow 运行子 DAG
- go - 为什么 Go 只使用环回接口发送我的多播数据包?
- react-native - React Native 中的 Flatlist 图像源
- javascript - 如何打印对象的值?