我需要过滤查询结果,以便其中一个选定的聚合字段满足特定条件。在这种情况下,让nvk.quality_id等于81或82. 81或81条件仅适用于我不计算其他字段的一个字段。此查询按预期工作:
SELECT
cams.name AS Campaign_Name,
clk.type,
COUNT(DISTINCT clk.eid) AS Dist_Eids_Sent,
COUNT(DISTINCT nvk.eid) AS Dist_Leads
FROM bm_arc.clicks156 clk
INNER JOIN bm_queue.campaigns cams ON clk.camp = cams.id
LEFT JOIN bm_emails.nvk156 nvk ON nvk.eid = clk.eid AND quality_id IN (81,82) # Hot, Warm
GROUP BY Campaign_Name, type
此处的结果如下所示:
Campaign Name | type | Dist_Eids_Sent | Dist_Leads
dogs | 1 | 1000 | 100
cats | 1 | 900 | 80
这些结果是正确的,符合我们的期望。 81和82是Dist_Leads类型的描述。我们希望结果中有热门或热门。
但是,而不是说AND quality_id IN (81,82) # Hot, Warm
我想在选择器中使用这两个ID的英文含义。
要做到这一点,我必须加入查询
bm_config.classes cls ON nvk.quality_id = cls.id AND (cls.cid = 156 AND cls.name IN ('Hot', 'Warm'))
这看起来像:
SELECT
cams.name AS Campaign_Name,
clk.type,
COUNT(DISTINCT clk.eid) AS Dist_Eids_Sent,
COUNT(DISTINCT nvk.eid) AS Dist_Leads
FROM bm_arc.clicks156 clk
INNER JOIN bm_queue.campaigns cams ON clk.camp = cams.id
LEFT JOIN bm_emails.nvk156 nvk ON nvk.eid = clk.eid
LEFT JOIN bm_config.classes cls ON nvk.quality_id = cls.id AND cls.name IN ('Hot', 'Warm'))
GROUP BY Campaign_Name, type
但结果看起来像这样:
Campaign Name | type | Dist_Eids_Sent | Dist_Leads
dogs | 1 | 1000 | 990
cats | 1 | 900 | 850
然而,在Dist_Leads为Dist_Eids_Sent的约10%之前,它现在约为90%+
我不明白这里发生了什么。看起来附加连接正在连接到基表clk并改变结果
是否可以将我的LEFT JOIN编辑到nvk上,以便此连接仅适用于与cls.name相对应的记录" hot"或者"温暖"。 A"嵌套连接"如果你愿意的话。
它看起来像这样:
LEFT JOIN bm_emails.nvk156 nvk ON nvk.eid = clk.eid AND
bm_config.classes cls ON nvk.quality_id = cls.id AND
(cls.cid = 156 AND cls.name IN ('Hot', 'Warm')
希望我要求的是有道理的。我基本上试图将所有过滤添加到一个左连接中,以免影响其余的查询结果。
答案 0 :(得分:1)
如果那不太正确,请原谅我。我通常不会使用MySql!
SELECT
cams.name AS Campaign_Name,
clk.type,
COUNT(DISTINCT clk.eid) AS Dist_Eids_Sent,
COUNT(DISTINCT nvk.eid) AS Dist_Leads
FROM bm_arc.clicks156 clk
INNER JOIN bm_queue.campaigns cams ON clk.camp = cams.id
LEFT JOIN
( SELECT
eid
FROM bm_emails.nvk156
INNER JOIN bm_config.classes cls ON nvk.quality_id = cls.id
WHERE cls.name IN ('Hot', 'Warm')
) nvk ON nvk.eid = clk.eid
GROUP BY Campaign_Name, type