简体   繁体   中英

MySQL Subquery SUM Limit

I'm trying to do an subquery with SUM() and LIMIT. This works fine with the following code:

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

But I want to do it of course dynamically and with the current row ID. I changed the Query to the following:

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

This will give the following error:

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

Any ideas how to make it working?

why not just change p.id to t1.id? I'm pretty sure it's because you are aliasing t1 in the first select, and it isn't defined in the subquery. Try an inner join instead.

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

Unfortunately, MySQL limits the scope of table aliases. Oracle is another database that does this.

You can phrase your query as a complicated join:

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;

Or you can do this with variables:

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;

Try this:

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

I moved subqueries in the join part, so i can access to p.id in the subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM