Martin Kadlcek
Martin Kadlcek

Reputation: 15

Two columns working with same data

I have problem with my SQL query.

I have two tables - the first one has ID and ID of persons:

id | id_p | id_p2
1  |   1  |  2
2  |   2  |  3
...

In the second one, I have ID of Persons and their names

id_p | name
1    | John
2    | Alice
3    | Daniel
...

What I need - I need to get one SQL query, which will return back to me name of persons, but every id_p in a different column. So I need id_p with names and id_p2 with names too. Example here

id | id_p | id_p2 | name_p | name_p2
1  |   1  |   2   |  John  |  Alice
2  |   2  |   3   |  Alice |  Daniel
...

How can I do this? Many thanks!

Upvotes: 1

Views: 49

Answers (1)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You need SELF JOIN :

select t.id, p.name as FirstIdPerson, p2.name as SecondIdPerson
from table t inner join
     person p
     on p.id_p = t.id_p inner join 
     person p2
     on p2.id_p = t.id_p2;

Upvotes: 1

Related Questions