2014-06-09 164 views
1

我有一個需求,我需要o組數據到相同的ob行。由於MySQL沒有rownum()我模仿這種行爲:MySQL左側加入子查詢組

SET @row:=6; 
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count 
FROM 
    (
     SELECT timestamp, value, @row:[email protected]+1 AS row 
     FROM data 
     WHERE channel_id=52 AND timestamp >= 0 ORDER BY timestamp 
    ) AS agg 
GROUP BY row div 8 
ORDER BY timestamp ASC; 

注:根據Can grouped expressions be used with variable assignments?此查詢可能不是100%正確的,但它確實工作

另一個要求是計算分組集合之間的行差異。我找了一個解決方案使用子查詢加入同一個表:

SET @row:=6; 
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count 
FROM 
    (
     SELECT timestamp, value, @row:[email protected]+1 AS row 
     FROM data 
     WHERE channel_id=52 AND timestamp >= 0 ORDER BY timestamp 
    ) AS agg 
LEFT JOIN data AS prev 
    ON prev.channel_id = agg.channel_id 
    AND prev.timestamp = (
     SELECT MAX(timestamp) 
     FROM data 
     WHERE data.channel_id = agg.channel_id 
      AND data.timestamp < MIN(agg.timestamp) 
    ) 
GROUP BY row div 8 
ORDER BY timestamp ASC; 

不幸的錯誤:

Error Code: 1054. Unknown column 'agg.channel_id' in 'on clause' 

任何想法如何查詢可以寫?

+0

它應該只是在'agg'子查詢的選擇列表中公開'channel_id'。當前你只有在'WHERE'子句中。 (我沒有分析是否會給你想要的結果,但它會清除1054錯誤) –

回答

0

這個怎麼樣版:

SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count, COALESCE(prev.timestamp, 0) AS prev_timestamp 
FROM (SELECT d.*, @row:[email protected]+1 AS row 
     FROM data d CROSS JOIN 
      (select @row := 6) vars 
     WHERE channel_id = 52 AND timestamp >= 0 ORDER BY timestamp 
    ) agg LEFT JOIN 
    data prev 
    ON prev.channel_id = agg.channel_id AND 
     prev.timestamp = (SELECT MAX(timestamp) 
         FROM data 
         WHERE data.channel_id = agg.channel_id AND 
           data.timestamp < agg.timestamp 
         ) 
GROUP BY row div 8 
ORDER BY timestamp ASC; 

這包括在子查詢中的所有列。它將變量初始化放在同一個查詢中。

+0

我喜歡交叉連接,但是「錯誤代碼:1111.無效的組功能使用」 – andig

+0

@andig。 。 。這是你的子查詢。我不確定應該做什麼,但是不能在「from」子句中放置相關的子查詢。 –

+0

我需要子查詢來計算時間戳行與前一個聚合行的行差異。我已經重寫了您的答案,以消除錯誤並提供期望的結果。 – andig

2

您從未從您的sbuquery中選擇channel_id,因此它不會返回到父查詢中,因此不可見。嘗試

SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count 
FROM 
    (
     SELECT timestamp, value, @row:[email protected]+1 AS row, channel_id 
                ^^^^^^^^^^^^-- need this 
     FROM data 

因爲MySQL只看到並使用您從子查詢返回明確的領域,並不會「深入挖掘」到表中查詢底層,您需要選擇/返回所有你的領域正在使用父查詢。