2015-11-08 50 views
1

我有一個視圖,它是兩個表的連接,我需要該視圖中的額外列 - cum_profit。MySQL存儲在VIEW中的兩個表的JOIN的累積和

我得到了一個解決方案,它爲我做了,但我無法將它保存爲視圖,因爲「視圖的SELECT包含FROM子句中的子查詢」。

這是代碼: 注:cumulative_profit是

SELECT *, cum_profit 
FROM cumulative_profit 
INNER JOIN 
    (
    SELECT match_id, 
    @cum:[email protected]+profit as cum_profit 
     FROM cumulative_profit 
     JOIN (SELECT @cum:=0) init 
    ORDER BY match_date, ko_time, match_id 
    ) cum USING (match_id) 
ORDER BY match_date DESC, ko_time DESC, match_id DESC; 

Tables and view

我試圖用其他方式提出了例如計算累計總和的VIEW使用類似的代碼如下:

SELECT t.id, 
     t.count, 
     (SELECT SUM(x.count) 
      FROM TABLE x 
      WHERE x.id <= t.id) AS cumulative_sum 
    FROM TABLE t 
ORDER BY t.id 

但我沒能使其與我的表和視圖的工作。

有沒有人有任何想法或建議?

謝謝

回答

0

下應相當於第一條語句(假設match_id是唯一的),並在視圖中工作:

SELECT cp.*, 
     (SELECT SUM(cp2.profit) 
     FROM cumulative_profit cp2 
     WHERE (cp2.match_date < cp.match_date) OR 
       (cp2.match_date = cp.match_date AND cp2.ko_time < cp.ko_time) OR 
       (cp2.match_date = cp.match_date AND cp2.ko_time = cp.ko_time AND cp2.match_id <= cp.match_id) 
     ) as cumulative_profit 
FROM cumulative_profit cp 
ORDER BY match_date DESC, ko_time DESC, match_id DESC; 
+0

此查詢有子查詢,所以你可能無法創建從它看來 –

+0

謝謝。 MySQL返回... #1051 - 未知表'cp' 我嘗試執行您的建議時遇到了同樣的問題。它會在一個視圖中工作嗎? – Darius

+0

@PiniCheyni。 。 。子查詢的限制只在'FROM'子句中。 –