2014-07-08 269 views
1

我想用SUM()和LIMIT做一個子查詢。這與以下代碼正常工作:MySQL子查詢SUM限制

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' 

任何想法如何使它工作?

+2

請提供樣本數據和預期輸出。 – Uriil

回答

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; 
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 
+0

沒有區別。 – Dev0r

+0

內部連接不工作? –

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。