在連接語句中選擇最近的日期:歷史位置資料檢索故障排除
此查詢旨在檢索記錄的歷史位置和他們對應的日期。然而,當前的實作需要很長的時間來執行並產生重複的記錄。預期輸出是一個簡化的記錄清單及其最近位置。
原始查詢嘗試透過執行自連線操作來尋找與每個記錄 ID 關聯的最新日期。然而,這種方法效率低下,可能會導致效能問題,尤其是對於較大的資料集。
正確查詢
要最佳化查詢,我們可以利用以下更正後的查詢版本:
SELECT t1.received_id , t1.transaction_id , t1.date_modified , l.location FROM transactions t1 JOIN ( SELECT received_id, MAX(date_modified) maxmodify FROM transactions GROUP BY received_id) max_record ON max_record.received_id = t1.received_id AND max_record.maxmodify = t1.date_modified JOIN locations l ON l.location_id = t1.location_id JOIN received r ON r.received_id = t1.received_id WHERE t1.received_id = '1782' ORDER BY t1.date_modified DESC
解釋
解釋SELECT received_id, MAX(date_modified) AS maxmodify FROM transactions GROUP BY received_id
以上是如何有效率地檢索連接語句中每筆記錄的最新位置資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!