Select Inner Join of what is not in the other table

Asked

Viewed 224 times

2

I have two tables, Anuidades and Pagamentos.
Of these annuities it is necessary to select the data of Anuidades which have not yet been paid.

Table Anuidades

inserir a descrição da imagem aqui

Table Pagamentos

inserir a descrição da imagem aqui

To return the annuities data that had been paid I used the following query:

SELECT * 
FROM anuidades
INNER JOIN pagamentos ON anuidades.Id = pagamentos.idAnuidade
WHERE pagamentos.idMinistro = 1

and he returned correctly: inserir a descrição da imagem aqui

But when I try to select the annuities that have no record in the payments table I cannot.

2 answers

5

Try it this way:

SELECT anuidades.* 
FROM anuidades
LEFT JOIN pagamentos ON anuidades.Id = pagamentos.idAnuidade
WHERE pagamentos.idMinistro = 1
AND pagamentos.idAnuidade Is null
  • It didn’t work, it returns empty =/

1


There is more than one way to make this select, it follows some forms:

LEFT OUTER JOIN

SELECT * FROM ANUIDADES
LEFT JOIN PAGAMENTOS 
    ON ANUIDADES.Id = PAGAMENTOS.idAnuidade
WHERE PAGAMENTOS.idAnuidade IS NULL

NOT EXISTS

SELECT * FROM ANUIDADES
WHERE NOT EXISTS (
            SELECT NULL FROM PAGAMENTOS
                WHERE   PAGAMENTOS.IDMINISTRO = 1
                AND     PAGAMENTOS.IDANUIDADE = ANUIDADES.ID)

NOT IN

SELECT * FROM ANUIDADES
WHERE ANUIDADES.ID NOT IN (
                        SELECT IDANUIDADE FROM PAGAMENTOS
                        WHERE IDMINISTRO = 1)

Note: LEFT JOIN / IS NULL and NOT EXISTS are semantically equivalent, while NOT IN is not.

  • Show!! The first of LEFT OUTER JOIN returned empty, but the other two, NOT EXISTS and NOT IN worked perfectly!! Thank you very much!!

  • I’m glad it worked. However LEFT OUTER JOIN should work as well, simulated with the same tables you provided and returned the same as the other 2 examples. Remember that in LEFT OUTER JOIN you can not put WHERE/AND PAGAMENTOS.IDMINISTRO = 1 because with it will return empty even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.