1

I was wondering is there a better way to write this particular query

SELECT flights.id as flightid,
                flights.icao, 
                aircraft.reg_no AS regno,
                starttime,
                endtime,
                originloc.country_code as origincountry,
                originloc.name_en AS originloc,
                destloc.country_code as destcountry,
                destloc.name_en AS destloc,
                (select pings.call from pings where pings.call != 'null' and pings.flightid = flights.id limit 1) as flightcall
                 FROM flights LEFT JOIN localities_sys originloc ON originloc.id = flights.originloc LEFT JOIN localities_sys destloc
                 ON destloc.id = flights.destloc LEFT JOIN aircraft ON aircraft.icao = flights.icao

If I try to add a condition at the end such as

 WHERE flightcall = 'test'

I get an error stating that ERROR: column "flightcall" does not exist

Any help is greatly appreciated

Thanks Damien

4
  • Your flightcall subquery is using LIMIT without ORDER BY, which is fairly meaningless. Please explain the logic of this subquery. Commented Mar 29, 2020 at 12:19
  • there are multiple entries in the ping table for each flight. I want to return only 1 of the calls. The calls colum will be the same in each row however there are some nulls in there unfortunately Commented Mar 29, 2020 at 12:25
  • What is the logic for which one call gets selected, or does it truly not matter? Commented Mar 29, 2020 at 12:35
  • yeah which one selected truly doesnt matter Commented Mar 29, 2020 at 12:36

1 Answer 1

1

Alises in where clause are not supported in PostgreSQL. You either have to use the nested query or use below query -

SELECT flights.id as flightid,
       flights.icao, 
       aircraft.reg_no AS regno,
       starttime,
       endtime,
       originloc.country_code as origincountry,
       originloc.name_en AS originloc,
       destloc.country_code as destcountry,
       destloc.name_en AS destloc,
       (select pings.call
        from pings
        where pings.call != 'null'
        and pings.flightid = flights.id
        limit 1) as flightcall
FROM flights
LEFT JOIN localities_sys originloc ON originloc.id = flights.originloc
LEFT JOIN localities_sys destloc ON destloc.id = flights.destloc
LEFT JOIN aircraft ON aircraft.icao = flights.icao
WHERE pings.call = 'test';
Sign up to request clarification or add additional context in comments.

2 Comments

this is a postgres query not for MySql
@Damien, apologies for typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.