开发者

MySQL - LEFT JOIN and NOT IN

I try to avoid subqueries due to the fact they usually have much lower performance than a proper join.

This is my current NOT working query:

SELECT 
    a.`email_list_id`, a.`category_id`, a.`name`
FROM 
    `email_lists`AS a 
    LEFT JOIN `email_autoresponders` AS b 
        ON ( a.`website_id` = b.`website_id` ) 
WHERE 
    a.`website_id` = [...]
    AND a.`category_id` <> 0 
    AND a.`email_list_id` <> b.`ema开发者_开发技巧il_list_id` 
GROUP BY 
    a.`email_list_id` 
ORDER BY a.`name`

This query works:

SELECT 
    `email_list_id`, `category_id`, `name` 
FROM 
    `email_lists` 
WHERE 
    `website_id` = [...] 
    AND `category_id` <> 0 
    AND `email_list_id` NOT IN ( 
        SELECT 
            `email_list_id` 
        FROM 
            `email_autoresponders` 
        WHERE `website_id` = [...] 
    ) 
GROUP BY 
    `email_list_id` 
ORDER BY 
    `name` 

Is there any way to do this with a left join? I've tried a number of different options.


After rethinking it a bit, this might work i believe:

SELECT 
    a.`email_list_id`, a.`category_id`, a.`name`
FROM 
    `email_lists`AS a 
    LEFT JOIN `email_autoresponders` AS b 
        ON ( a.`website_id` = b.`website_id` and a.`email_list_id` = b.`email_list_id` ) 
WHERE 
    a.`website_id` = [...]
    AND a.`category_id` <> 0 
    AND b.`email_list_id` is NULL
GROUP BY 
    a.`email_list_id` 
ORDER BY a.`name`


For starters, add the inequality check on email_list_id to the join criteria, instead of having it in your WHERE clause:

LEFT JOIN `email_autoresponders` AS b 
    ON ( a.`website_id` = b.`website_id` 
         AND a.`email_list_id` <> b.`email_list_id` ) 

Though I'm not sure the scenario you mention calls for vast optimizations, this is a way to use a join rather than a subquery...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜