尝试创建查询以选择批处理超时时未通过电子邮件发送新闻稿的用户。 mail_log表捕获来自3个不同邮件列表的条目,并维护过去4-5周的日志 - 换句话说,每个订阅者应该有多个日志条目。
我希望选择在发送时批量超时时未通过电子邮件发送的所有订阅者。
mail_log
+--------+------------+-------------+------------+---------+
| log_id | send_date | location_id | mailing_id | list_id |
+--------+------------+-------------+------------+---------+
location_id is which mailing list
mailing_id is the specific newsletter
list_id is the subscriber's id in the mailing list
mail_list
+---------+-------+-------+-------+
| list_id | fname | lname | email |
+---------+-------+-------+-------+
我试过这个问题:
SELECT mail_list.*
FROM mail_list
LEFT JOIN mail_log ON mail_log.list_id = mail_list.list_id
WHERE mail_log.send_date = '2016-07-12'
AND mail_log.location_id = '2'
AND mail_log.list_id IS NULL`
查询返回0结果,但成功的查询应返回约700个结果。
答案 0 :(得分:2)
使用LEFT JOIN
时,必须将子表的限制放入ON
子句中。否则,当您测试这些字段时,您只会匹配非NULL行,这与AND mail_log.list_id IS NULL
测试相矛盾。
SELECT mail_list.*
FROM mail_list
LEFT JOIN mail_log ON mail_log.list_id = mail_list.list_id
AND mail_log.send_date = '2016-07-12'
AND mail_log.location_id = '2'
WHERE mail_log.list_id IS NULL
答案 1 :(得分:0)
SELECT * FROM mail_list WHERE list_id NOT IN(SELECT list_id FROM mail_log WHERE mailing_id =' 216')
更糟糕,因为使用NOT IN时,不会使用任何索引。使用左连接查询可以使用list_id,send_date和location_id作为连接的可能索引。