Avoid SQL WHERE NOT IN Clause

pengemizt picture pengemizt · Nov 6, 2011 · Viewed 8.7k times · Source

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?

Answer

GregM picture GregM · Nov 6, 2011

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