在 MySQL 的 Join 語句中查詢最大日期
要擷取 MySQL 中記錄的歷史位置,您可以使用 JOIN 語句。但是,當遇到效能問題和結果中存在重複資料時,需要修改方法。
修改查詢
只擷取每個記錄 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
Key修改
修改位於子查詢:
SELECT received_id, MAX(date_modified) maxmodify FROM transactions GROUP BY received_id
此子查詢會檢索每個received_id的最大日期。
加入最大值
然後主查詢使用兩個連接到這個子查詢條件:
以上是如何使用JOIN語句有效率地查詢MySQL中最新的位置資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!