2016-09-20 79 views
0

我有一個SQL查詢,在我看來,時間過長,現在看起來大概需要30秒。我有兩個表,RecordMainrecord。我想獲得關於列數量爲0的所有Mainrecords的信息,並且在那種情況下獲得最新的Record,其具有與其自己的數量中的其他值不同的0的相同ID。我有大約30,000條主記錄和大約3,000,000條記錄。我想這可以通過某種方式進行優化,但我無法弄清楚。表之間的內部連接,耗時

SELECT * 
FROM (
    mainrecord 
    INNER JOIN (
     SELECT tt.* 
     FROM record tt 
     INNER JOIN (
      SELECT Max(record.timestamp) AS maxtimestamp, id 
      FROM record 
      WHERE record.amount <> 0 
      GROUP BY record.id 
     ) AS rec 
     ON tt.id = rec.id AND tt.timestamp = rec.maxtimestamp 
    ) AS t 
    ON mainrecord.id = t.id 
) 
WHERE amount = 0 

說明:

+----+-------------+------------+-------------+---------------+-----------+---------+---------------------+---------+----------+---------------------------------------+ 
| id | select_type | table | type  | possible_keys | key | key_len |   ref   | rows | filtered |     Extra     | 
+----+-------------+------------+-------------+---------------+-----------+---------+---------------------+---------+----------+---------------------------------------+ 
| 1 | PRIMARY  | Mainrecord | index_merge | Id,Amount  | Amount |  768 | \N     | 2850 | 100,00 | Using sort_union(Amount); Using where | 
| 1 | PRIMARY  | <derived3> | ref   | key0   | key0  |  768 | db.Mainrecord.Id |  53 | 100,00 | Using where       | 
| 1 | PRIMARY  | tt   | ref   | Id,timestamp | timestamp |  9 | record.maxtimestamp |  1 | 100,00 | Using where       | 
| 3 | DERIVED  | Record  | index  | Amount  | Id  |  768 | \N     | 3185669 | 50,03 | Using where       | 
+----+-------------+------------+-------------+---------------+-----------+---------+---------------------+---------+----------+---------------------------------------+ 
+1

你的任何指標?另外,請添加'解釋'結果的問題。 – Shaharyar

+0

誰是主記錄表!? –

+0

@Shaharyar,id和amout都是這兩個表中的關鍵字。 – Nick3

回答

0

這個是什麼?爲了從子查詢

分組更新:

SELECT * 
FROM mainrecord mr 
    INNER JOIN (SELECT Max(record.timestamp) AS maxtimestamp, id 
     FROM record 
     WHERE record.amount <> 0 
     GROUP BY record.id) AS max_r ON max_r.id=mr.id 
    INNER JOIN record r ON mr.id = r.id 
WHERE mr.amount = 0 
    AND r.timestamp = max_r.maxtimestamp 
+0

謝謝,但我沒有得到它的工作。我想'FROM Record'應該是'FROM record tt'。由於括號的數量不匹配,我還在'rec.maxtimestamp'後刪除了''''。我現在得到的錯誤是語法錯誤:'AS max_r ON max_r.id = mr.id INNER JOIN記錄r ON mr.id = r.id' – Nick3

+0

我無法正確檢查sytax。請創建SQlFiddle,以便我可以測試查詢 – StanislavL

+0

http://sqlfiddle.com/#!9/430e02/1/0測試,我添加了一個非常簡單的結構,其中包含我們使用的所有元素。 – Nick3