试图在MySQL SubSubQuery中使用ID

时间:2013-07-23 15:20:53

标签: mysql subquery

所以我会告诉你我正在尝试做什么并解释我的问题,可能会有一个与我想要采取的方法不同的答案。

我正在尝试执行的查询如下:

SELECT *
FROM report_keywords rk
WHERE rk.report_id = 231
AND (
    SELECT SUM(t.conv) FROM (
        SELECT conv FROM report_keywords t2 WHERE t2.campaign_id = rk.campaign_id ORDER BY conv DESC LIMIT 10
    ) t
) >= 30
GROUP BY rk.campaign_id

我得到的错误是

Unknown column 'rk.campaign_id' in 'where clause'

显然这就是说表别名rk没有进入子查询。我要做的是获得所有前十次转化总和大于或等于30的广告系列。

相关的表格结构是:

id INT,
report_id INT,
campaign_id INT,
conv INT

非常感谢任何帮助。

更新

感谢Kickstart,我能够做我想做的事。这是我的最终查询:

SELECT campaign_id, SUM(conv) as sum_conv
FROM (
    SELECT campaign_id, conv, @Sequence := if(campaign_id = @campaign_id, @Sequence + 1, 1) AS aSequence, @campaign_id := campaign_id
    FROM report_keywords
    CROSS JOIN (SELECT @Sequence :=  0, @campaign_id := 0) Sub1
    WHERE report_id = 231
    ORDER BY campaign_id, conv DESC
) t
WHERE aSequence <= 10
GROUP BY campaign_id
HAVING sum_conv >= 30

1 个答案:

答案 0 :(得分:2)

可能使用用户变量添加序列号以获取每个序列号的最新10条记录,然后使用SUM来获取这些记录的数量。

这样的事情: -

SELECT rk.*
FROM report_keywords rk
INNER JOIN
(
    SELECT campaign_id, SUM(conv) AS SumConv
    FROM 
    (
        SELECT campaign_id, conv, @Sequence := if(campaign_id = @campaign_id, @Sequence + 1, 1) AS aSequence, @campaign_id := campaign_id
        FROM report_keywords
        CROSS JOIN (SELECT @Sequence :=  0, @campaign_id := "") Sub1
        ORDER BY campaign_id, conv
    ) Sub2
    WHERE aSequence <= 10
    GROUP BY campaign_id
) Sub3
ON rk.campaign_id = Sub3.campaign_id AND Sub3.SumConv >= 30
WHERE rk.report_id = 231