我有一個SQL查詢,在我看來,時間過長,現在看起來大概需要30秒。我有兩個表,Record
和Mainrecord
。我想獲得關於列數量爲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 |
+----+-------------+------------+-------------+---------------+-----------+---------+---------------------+---------+----------+---------------------------------------+
你的任何指標?另外,請添加'解釋'結果的問題。 – Shaharyar
誰是主記錄表!? –
@Shaharyar,id和amout都是這兩個表中的關鍵字。 – Nick3