我有兩個查詢,它們各自運行得非常快(少於2秒)。但是,當我嘗試將它們作爲子查詢加入時,它運行的速度很慢,速度很慢。上次我跑了它大概需要68秒。以下是完整的查詢:兩個查詢分開執行速度很快,加入子查詢時速度很慢
SELECT t.count,
t.total
FROM (SELECT t.account_number,
COUNT(t.id) count,
SUM(t.amount) total,
ib.id import_bundle_id
FROM import_bundle ib
JOIN generic_import gi ON gi.import_bundle_id = ib.id
JOIN transaction_import ti ON ti.generic_import_id = gi.id
JOIN account_transaction t ON t.transaction_import_id = ti.id
JOIN transaction_code tc ON t.transaction_code_id = tc.id
WHERE tc.code IN (0, 20, 40)
GROUP BY t.account_number) t
JOIN (SELECT a.account_number,
np.code
FROM import_bundle ib
JOIN generic_import gi ON gi.import_bundle_id = ib.id
JOIN account_import ai ON ai.generic_import_id = gi.id
JOIN account a ON a.account_import_id = ai.id
JOIN account_northway_product anp ON anp.account_id = a.id
JOIN northway_product np ON anp.northway_product_id = np.id
WHERE np.code != 'O1') a ON t.account_number = a.account_number
該查詢應該運行緩慢並不總是令人驚訝。如果這些是兩個單獨的表而不是子查詢,我會在其account_number
列上放置索引。但是,顯然不可能將索引放在查詢結果中,所以我不能這樣做。我懷疑這是問題的一部分。
除此之外,我不明白爲什麼查詢速度慢,我沒有任何關於如何加快速度的想法,除了添加兩個彙總表,我不想這樣做,如果我不必。
順便說一句,這個英語查詢可能是「獲取所有POS交易(代碼0,20和40)帳戶不透支保護帳戶(代碼O1)」。
請顯示您的解釋結果和您的表結構 – Neo 2011-04-19 13:43:42
第二個查詢是否可以在'account_number'返回重複項? – Quassnoi 2011-04-19 13:44:31