简体   繁体   中英

postgresql left join and order by

I am running the following query to extract data from a table (2018_01 in the example below) according to a matching with a coding system stored in another table (Registy_2018_DEF in the example below):

COPY (Select a.mmsi, a.locdate, a.loctime, a.lon, a.lat
from "2018_01" a
left join "Registry_2018_DEF" b
using (mmsi)
WHERE b.stcodedef = '0')
TO 'C:\AIS_DEF\DEF\FINAL\2018\2018_01\csv_ship_types\st_0_2018_01.csv' DELIMITER ';' CSV HEADER;

It works perfeclty but the records in the resulting csv are not always sorted. I would like that the resulting csv output be sorted by mmsi (ASC), by locdate (ASC) and finally by loctime (ASC). mmsi column is numeric type, locdate is date and loctime is text;

how can I do it? Thank you

Why not just add an ORDER BY clause to the query?

COPY (
    select a.mmsi, a.locdate, a.loctime, a.lon, a.lat
    from "2018_01" a
    left join "Registry_2018_DEF" b using (mmsi)
    where b.stcodedef = '0'
    order by a.mmsi, a.locdate, a.loctime
) TO 'C:\AIS_DEF\DEF\FINAL\2018\2018_01\csv_ship_types\st_0_2018_01.csv' 
    DELIMITER ';' 
    CSV HEADER;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM