Have you tried
AND (sn.notafiscalnumero, sn.notafiscalserie, sn.cliente) NOT IN (
SELECT numero, serie, codigo FROM r_contrato WHERE savfonte = 'lg')
or
and not exists(select true from r_contrato where savfonte = 'lg' and numero =
sn.notafiscalnumero and serie = sn.notafiscalserie and codigo = s
You're doing a join except not, is the trouble, looks like. The query is really
"FROM Tickets main, Links", but when Tickets.id is 17417, you've got no join
to the Links table. So you end up getting every row in Links for each row in
Tickets with id = 17417.
I'd think this wants to be two queries o