我试图在1个SELECT查询中做两件事(我知道我可以分两步完成这个但我想避免中间表):
我不确定语法是否正确,因为查询是永远加载的。但是,大小不应该是一个问题(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
答案 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