MySQL子查询SUM限制

时间:2014-07-08 14:33:40

标签: mysql sql

我试图用SUM()和LIMIT做一个子查询。这可以使用以下代码正常工作:

SELECT id, 
    (
        SELECT SUM(number) 
        FROM (
            SELECT number 
            FROM t2
            WHERE u_id = '1' 
            ORDER BY time ASC 
            LIMIT 30
        ) AS temp
    )  AS test
FROM t1

但我当然希望动态地使用当前行ID。 我将查询更改为以下内容:

SELECT id, 
    (
        SELECT SUM(number) 
        FROM (
            SELECT number
            FROM t2 
            WHERE u_id = p.id 
            ORDER BY time ASC 
            LIMIT 30
        ) AS temp
    )  AS test
FROM t1 p

这将产生以下错误:

Unknown column 'p.id' in 'where clause'

任何想法如何让它发挥作用?

3 个答案:

答案 0 :(得分:0)

为什么不将p.id更改为t1.id?我很确定这是因为你在第一个选择中使用了别名t1,并且它没有在子查询中定义。请尝试使用内部联接。

SELECT id, 
    (
        SELECT SUM(number) 
        FROM (
            SELECT number
            FROM t2 
            INNER JOIN t1 p
            on u_id = p.id 
            ORDER BY time ASC 
            LIMIT 30
        ) AS temp
    )  AS test
FROM t1 p

答案 1 :(得分:0)

不幸的是,MySQL限制了表别名的范围。 Oracle是另一个实现此目的的数据库。

您可以将查询标记为复杂的联接:

select t1.id, sum(t2.number)
from t1 p join
     t2
     on p.id = t2.u_id
where 30 >= (select count(*)
             from t2 t22
             where t22.u_id = t2.u_id and
                   t22.time <= t2.time
            )
group by t1.id;

或者您可以使用变量执行此操作:

select p.id, sum(number)
from t1 p join
     (select t2.*,
             @rn := if(@u = t2.u_id, @rn + 1, if((@u := t2.u_id) is not null, 1, 0)) as rn
      from t2
           (select @u := 0, @rn := 0) vars
      order by t2.u_d, time
     ) t2
     on p.id = t2.u_id
where rn <= 30
group by p.id;

答案 2 :(得分:0)

试试这个:

SELECT id, temp2.sum_number as test
FROM t1 p
INNER JOIN
(
    SELECT SUM(number) as sum_number, temp.u_id
        FROM (
            SELECT number, u_id
            FROM t2 
            WHERE u_id = p.id 
            ORDER BY time ASC 
            LIMIT 30
        ) AS temp
)  AS temp2 ON temp2.u_id = p.id

我在连接部分中移动了子查询,因此我可以访问子查询中的p.id.