子查询中的MySQL未知列

时间:2016-02-23 10:54:50

标签: mysql subquery

我正在尝试在MySQL中只用两列contestsid(int)来实现表ideas_count的“滚动平均值”:

contests中的每一行返回id以及前一行(包括当前行)前10行的平均值ideas_count

这是我被困的地方:

select 
  id, (
    select avg(ideas_count) from (
      select * from contests c2 where c2.id<=c1.id order by id desc limit 10
    ) prev
  ) 
from 
  contests c1
order by 
  id asc;

MySQL返回错误:“Unknown column 'c1.id' in 'where clause'

为什么?

我该如何做到这一点?

更新

select 
  id, (
    select avg(ideas_count) from contests c2 
    where c2.id <= c1.id order by id desc limit 10
  ) 
from 
  contests c1
order by 
  id asc;

工作,因为它首先计算avg 并在之后应用limit ,而我需要最后10行的平均值

更新2

添加了SQLFiddle

3 个答案:

答案 0 :(得分:3)

使用在子查询中生成的几个序列号。然后根据这些序列号加入子查询。

SELECT sub1.id, 
        AVG(sub2.ideas_count) AS rolling_average
FROM
(
    SELECT id, ideas_count, @seq1:=@seq1 + 1 AS seq
    FROM contests
    CROSS JOIN (SELECT @seq1:=0) sub0
    ORDER BY id
) sub1
INNER JOIN
(
    SELECT id, ideas_count, @seq2:=@seq2 + 1 AS seq
    FROM contests
    CROSS JOIN (SELECT @seq2:=0) sub0
    ORDER BY id
) sub2
ON sub2.seq BETWEEN sub1.seq -9 AND sub1.seq
GROUP BY sub1.id

答案 1 :(得分:1)

希望它可以提供帮助

select id , avg(ideas_count)
from (
    select t1.id, t1.t_id, t1.ideas_count, @i:=if(@j < t1.id, 1, @i+1) as i, @j:=t1.id as j
    from ( select c1.id, c2.id as t_id, c2.ideas_count
           from contests c2 join contests c1 on c2.id<=c1.id 
           order by c1.id asc, c2.id desc
        ) as t1
        join (select @i:=0, @j:=0) as t2
    ) as t3
where i <=10
group by id

答案 2 :(得分:0)

您可以将查询更新为:

select 
id, (select avg(ideas_count) from  
(select * from contests c2) prev where prev.id<=c1.id  order by prev.id desc limit 10 )     
as average 
from 
contests c1
order by id asc;