There is no secret - the SQL language was made to look English and only following the logic of its "Where" is it easy to understand that there will be no record for which the "a. subproject" is NULL and has a "NULL" equivalent in q.code. This query should work:
select a.codigo, q.nome as nomesubprojeto, a.subprojeto from
comprovante a, subprojeto q
where (a.subprojeto = q.codigo OR a.subprojeto IS NULL) AND a.codigo = 3
A more specific way, and that will be much more familiar to those who are already accustomed to SQL is to use the intermediate clause of "Join" to indicate the junction of tables before the clause "Where". In this case, since you want results from the table on the left even when there is no corresponding record, the correct is the LEFT JOIN
:
SELECT a.codigo, q.nome as nomesubprojeto, a.subprojeto
FROM comprovante as a
LEFT JOIN subprojeto as q
ON a.subprojeto = q.codigo
where a.codigo = 3
Why not use INNER JOIN or LEFT JOIN?
– Setimo Muteca Jr.
You want to make a
LEFT OUTTER JOIN
but is making aINNER JOIN
implicit. There is a p/ notation to do this implicitly but it is much better to get used to writing SQL in explicit notation– jean