Query to join specific tables

Asked

Viewed 110 times

-1

I need to put together three different tables. But the result I want is: When there is the reference it must join, when there must be no blank or NULL.

My structure:

Table contact

+------+------------+
|  ID  |    Nome    |
+------+------------+
|  1   | Contato #1 |
+------+------------+
|  2   | Contato #2 |
+------+------------+
|  3   | Contato #3 |
+------+------------+
|  4   | Contato #4 |
+------+------------+
|  5   | Contato #5 |
+------+------------+

Contact table

+------+------------+-----------------------------+
|  ID  | id_contato |           email             |
+------+------------+-----------------------------+
|  1   |      1     | [email protected] |
+------+------------+-----------------------------+
|  2   |      2     | [email protected] |
+------+------------+-----------------------------+
|  3   |      2     | [email protected] |
+------+------------+-----------------------------+

I did that Ner Join:

select * 
from contato
inner join contato_email on (contato.id_contato = contato_email.id_contato)

But with that it returns only the users who have an email.
Note that a user may have more than one associated email.
I want to search all contacts and if you have email I must join the data.

+------+------------+-----------------------------+
|  ID  |    Nome    |          email              |
+------+------------+-----------------------------+
|  1   | Contato #1 | [email protected] |
+------+------------+-----------------------------+
|  2   | Contato #2 | [email protected] |
+------+------------+-----------------------------+
|  2   | Contato #2 | [email protected] |
+------+------------+-----------------------------+
|  3   | Contato #3 |                             |
+------+------------+-----------------------------+
|  4   | Contato #4 |                             |
+------+------------+-----------------------------+
|  5   | Contato #5 |                             |
+------+------------+-----------------------------+

This is the desired return.
Thank you.

1 answer

5


Try replacing Inner with LEFT JOIN

select * 
from contato
left join contato_email on (contato.id_contato = contato_email.id_contato)
  • Wow. I was getting beat 30 minutes ago on this --' Thank you haha.

  • You’re welcome! It’s normal, I get it sometimes too!

Browser other questions tagged

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