首页 > 解决方案 > 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 个帖子,如果在一个查询中存在相似,然后插入那些不相似的。我知道这很复杂,但会是一个很好的查询。

非常感谢。

标签: phpmysqlsql

解决方案


您可以使用UNION ALL来制作一组您的个人FROM-less SELECTs,然后您可以将其用作一个派生表而不是 30 个。而不是INWHERE子句中使用,您可以直接关联。

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`);

推荐阅读