使用JOIN而不是NOT IN消除记录

时间:2016-03-29 02:58:29

标签: sql postgresql left-join

此查询的工作原理与我预期的一样,但我试图避免使用“not in”:

select * from subscribers ls join emailopens eo
    on ls.subscriberid=eo.subscriberid
    where ls.listid=1381 
    and opentime  > 1458864000
    and emailaddress not IN (select emailaddress from subscribers where listid=1384)

我试过这个:

select * from subscribers ls join emailopens eo
    on ls.subscriberid=eo.subscriberid left join subscribers ls2
    on ls.emailaddress=ls2.emailaddress
    where ls.listid=1381 
    and opentime  > 1458864000
    and ls2.listid=1384

问题是它只返回listid=1381listid=1384中具有相同电子邮件的行。我想,因为我使用左连接它应该返回所有行where listid=1381,然后在1384中同一封电子邮件的行上将有数据,但如果1381中有电子邮件1}}而非1384,会显示null列中的ls2.*

1 个答案:

答案 0 :(得分:1)

ls2.listid放入WHERE有效地将LEFT JOIN变为INNER JOIN。尝试在listid中保留ON约束,然后,为了产生NOT IN的效果,通过询问ls2.emailaddress IS NULL:<的记录,使其成为反连接/ p>

select * from subscribers ls join emailopens eo
    on ls.subscriberid=eo.subscriberid left join subscribers ls2
    on ls.emailaddress=ls2.emailaddress and ls2.listid = 1384
    where ls.listid=1381 
    and opentime  > 1458864000
    and ls2.emailaddress is null