Search code examples
sqlwhere-in

Avoid SQL WHERE NOT IN Clause


I have 3 tables listed below:

Blog    BlogArticle  Article
----    -----------  -------
        id
id------blog_id      -id
title   article_id__/ title

This SQL describe what I want:

SELECT * 
FROM  `article` 
WHERE  `article`.`id` NOT IN (
        SELECT CONCAT(`blog_article`.`article_id`) 
        FROM  `blog_article` 
        WHERE  `blog_article`.`blog_id` = 1 -- example value
       )

The problem is, I have a big NOT IN values in that case, and as far as i know it will impact to server performance (I'm not sure since I've never try to benchmark or Google it). Any suggestion?


Solution

  • Try this :

    SELECT * 
    FROM  `article` 
    LEFT JOIN `blog_article` ON CONCAT(`blog_article`.`article_id`) = `article`.`id`
                                AND  `blog_article`.`blog_id` = 1 -- example value
    WHERE `blog_article`.`article_id` is null --replace the not in