Good afternoon!
I have a SQL query and would like to get 2 additional fields from other tables, but with other names so they are not ambiguous.
See the last two subqueries to retrieve 2 fields as trtTituloOrigem
and trtTituloDestino
, respectively.
SELECT *,
(SELECT treNome FROM sistema_trecho treo WHERE tre.treId = voo.vooOrigemId) as treNomeOrigem,
(SELECT treEnderecoCidade FROM sistema_trecho treo WHERE treo.treId = voo.vooOrigemId) as treEnderecoCidadeOrigem,
(SELECT treEnderecoEstado FROM sistema_trecho treo WHERE treo.treId = voo.vooOrigemId) as treEnderecoEstadoOrigem,
(SELECT treNome FROM sistema_trecho tred WHERE tred.treId = voo.vooDestinoId) as treNomeDestino,
(SELECT treEnderecoCidade FROM sistema_trecho tred WHERE tred.treId = voo.vooDestinoId) as treEnderecoCidadeDestino,
(SELECT treEnderecoEstado FROM sistema_trecho tred WHERE tred.treId = voo.vooDestinoId) as treEnderecoEstadoDestino,
(SELECT trtTitulo FROM sistema_trecho_tipo trt WHERE trt.trtId = treo.trtId) as trtTituloOrigem,
(SELECT trtTitulo FROM sistema_trecho_tipo trt WHERE trt.trtId = tred.trtId) as trtTituloDestino
FROM sistema_voo_operadora vop
LEFT JOIN sistema_operadora ope ON vop.opeId = ope.opeId
LEFT JOIN sistema_voo voo ON vop.vooId = voo.vooId
LEFT JOIN sistema_tipo_voo tiv ON voo.tivId = tiv.tivId
LEFT JOIN sistema_aeronave aer ON vop.aerId = aer.aerId
WHERE ope.opeId = 2;
When I run this query, I'm getting the error:
Unknown 'tre.treId' column in 'where clause'
I believe it should be because treId
does not exist in the subquery , since I'm only having trtTitulo
, right? But how can I bring these two fields?
Just to explain the whole context:
1) I have a global flight schedule ( sistema_voo
)
2) I have a table of flights by operator ( sistema_voo_operadora
), saving the global flight ID ( vooId
)
3) In the table of global flights, I have the ID of the destination and source snippets. These IDs are from a table named sistema_trecho
( treId
).
As I need a query to bring both in the same place, so I do not have to do N queries, I would like to bring all the infos in one place. I know it's possible, but I do not know if this is the right way.
Attempts:
If I put in addition to trtTitulo
, a trtId
in the subqueries , they no longer work as well.