Memilih Tarikh Maksimum Dalam Operasi Sertai
Untuk mendapatkan semula lokasi bersejarah bagi rekod tertentu, pertimbangkan pertanyaan berikut:
SELECT l.location, t.transaction_id, t.date_modified FROM transactions AS t INNER JOIN ( SELECT received_id, MAX(date_modified) AS maxmodify FROM transactions GROUP BY received_id ) AS max_record ON ( t1.received_id = max_record.received_id ) INNER JOIN locations AS l ON ( l.location_id = t.location_id ) INNER JOIN received AS r ON ( r.received_id = t.received_id ) WHERE t.received_id = '1782' ORDER BY t.date_modified DESC;
Pertanyaan ini mengembalikan senarai lokasi untuk rekod tertentu, tetapi ia termasuk berbilang entri untuk lokasi yang sama dan tarikh. Untuk memastikan hanya tarikh terakhir diubah suai dipaparkan untuk setiap lokasi, gunakan pertanyaan berikut:
SELECT t1.received_id, t1.transaction_id, t1.date_modified, l.location FROM transactions t1 JOIN ( SELECT received_id, MAX(date_modified) AS maxmodify FROM transactions GROUP BY received_id ) AS max_record ON ( max_record.received_id = t1.received_id AND max_record.maxmodify = t1.date_modified ) JOIN locations AS l ON ( l.location_id = t1.location_id ) JOIN received AS r ON ( r.received_id = t1.received_id ) WHERE t1.received_id = '1782' ORDER BY t1.date_modified DESC;
Pengubahsuaian utama ialah penambahan syarat gabungan yang memastikan nilai date_modified yang dipilih adalah maksimum untuk setiap rekod . Ini memastikan bahawa hanya maklumat lokasi terkini yang dikemas kini dipaparkan.
Atas ialah kandungan terperinci Bagaimana untuk Memilih Hanya Data Lokasi Terkini Dalam SQL Join?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!