Compare items from different tables

Asked

Viewed 8,705 times

3

I have two tables:

Pessoa1                     Pessoa2
+----+--------+             +----+--------+
| Id |  Nome  |             | Id |  Nome  |
+----+--------+             +----+--------+
| 1  | Maria  |             | 3  | Maria  |
| 2  | João   |             | 4  | João   |
+----+--------+             | 5  | Pedro  |
                            +----+--------+

I would like to get the names that appear in the two tables.

Resultado
+--------+
|  Nome  |
+--------+
| Maria  |
| João   |
+--------+

2 answers

4


Since the ID of both tables are equal, you can do the following:

SELECT a.Nome FROM Pessoa1 a JOIN Pessoa2 b ON a.Id = b.Id;

Or exchange the Id for the Name, but the result would be the same and the ideal is to always use the identifier.

EDIT

According to the edition you asked in the question:

SELECT a.Nome FROM Pessoa1 a JOIN Pessoa2 b ON a.Nome = b.Nome;

2

You can use it INNER JOIN by the column Nome

SELECT Pessoa1.Nome FROM Pessoa1 INNER JOIN Pessoa2 ON (Pessoa1.Nome = Pessoa2.Nome)

EDIT:

Not ideal to use INNER JOIN without an indexed column, it can slow down the query depending on the amount of record you have in both tables.

  • Edited question, I need it based on name.

  • The query is based on the name, the only difference is that it brings the field Id in the result, just take the Pessoa1.Id in the query fields

Browser other questions tagged

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