在一次选择特定值时排除电子邮件列表

时间:2016-11-20 23:21:31

标签: mysql select exists

我试图在1个SELECT查询中做两件事(我知道我可以分两步完成这个但我想避免中间表):

  1. 从TABLE' anothertable'中选择特定值(仅限M和W - 可能还有其他值,但我只想要这些值而不是其他值)。
  2. 避免选择退出和退回电子邮件(11k行,<5列)。
  3. 我不确定语法是否正确,因为查询是永远加载的。但是,大小不应该是一个问题(27k行,<5列和2个核心处理器)。

    BEGIN
    
    CREATE TABLE `mytable` AS (
    
    SELECT * FROM `anothertable` A
    
    WHERE NOT EXISTS (SELECT Email FROM `optout` B WHERE B.Email = A.Email)
    AND NOT EXISTS (SELECT Email FROM `allbounced` C WHERE C.emailbounced = A.Email)
    
    GROUP BY Email
    HAVING 
    (SUM(CASE WHEN target = 'M' THEN 1 ELSE 0 END) > 0 OR   -- MAN  is present
    SUM(CASE WHEN target = 'W' THEN 1 ELSE 0 END) > 0 AND   -- WOMAN  is present
    SUM(CASE WHEN target NOT IN ('M', 'W') THEN 1 ELSE 0 END) = 0)  -- only MAN or WOMAN
    
    );
    
    END
    

1 个答案:

答案 0 :(得分:2)

如果可能,您应该使用NOT IN代替NOT EXISTS。这应该更快:

BEGIN

CREATE TABLE `mytable` AS (

SELECT Email FROM `anothertable` A
WHERE Email NOT IN (SELECT Email FROM `optout`)
AND Email NOT IN (SELECT emailbounced FROM `allbounced`)

GROUP BY Email
HAVING 
(SUM(CASE WHEN target = 'M' THEN 1 ELSE 0 END) > 0 OR   -- MAN  is present
SUM(CASE WHEN target = 'W' THEN 1 ELSE 0 END) > 0 AND   -- WOMAN  is present
SUM(CASE WHEN target NOT IN ('M', 'W') THEN 1 ELSE 0 END) = 0)  -- only MAN or WOMAN

);

END