I have that problem:
I have a model with those 3 tables:
Linha, Itinerario and Rua
Into Itinerario i have the reference id to Linha table and one reference with id for Rua.
In my code i recieve two arguments about idRua and i must return all Linhas where i have Itinerario the references for Rua with both idRua… In this examples where i have idRua = 1 and idRua = 2.
SELECT l.codigo, l.linha, l.idEmpresa, l.idLinha
FROM Linha l
INNER JOIN Itinerario i1 ON i1.idLinha = l.idLinha
INNER JOIN Itinerario i2 ON i2.idLinha = l.idLinha
WHERE i1.ida = i2.ida and i1.idRua = 1 and i2.idRua = 2
ORDER BY l.linha
The problem is that i get 2 inner join in that table Itinerario and the query gets to slow…
Is there somehow to optimize it?
Is there some “IN” operator with “AND” condition or something like this?
Im using SQLite.
There may be a way to eliminate the self-join.
If I’m reading this correctly, you want idLinha’s from Itinerario that contain both idRua = 1 and idRua = 2 for the same ida. I’m noticing that this is just a filter condition, since everything in the select comes from linha.
The following gets this condition:
Now, we can use this in an “in” or “join” clause, as in:
It is possible that the group by will be faster than a self-join.