我试图避免子查询,因为它们通常比正确的连接具有更低的性能。
这是我目前无效的查询:
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.`email_list_id`
GROUP BY
a.`email_list_id`
ORDER BY a.`name`
此查询有效:
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`
有没有办法用左连接做到这一点?我尝试了很多不同的选择。
答案 0 :(得分:2)
重新思考一下之后,我相信这可能有用:
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`
答案 1 :(得分:0)
对于初学者,将email_list_id
上的不等式检查添加到连接条件,而不是将其放在WHERE子句中:
LEFT JOIN `email_autoresponders` AS b
ON ( a.`website_id` = b.`website_id`
AND a.`email_list_id` <> b.`email_list_id` )
虽然我不确定你提到的场景需要大量优化,但这是一种使用连接而不是子查询的方法......