Optimaz Prime
Optimaz Prime

Reputation: 937

How use two Foreign Keys inside Single query?

I have 2 tables on database,'locations' & 'sales_person'.inside the 'location' table there are two columns name "location_from" & "location_to".Those 2 tables include primary keys of sales_person table as Foreign Keys.

enter image description here

the problem is, how to get both sales person names from sales_person table using only one query?

Upvotes: 0

Views: 48

Answers (2)

Max
Max

Reputation: 19

You can also use union for single query.

select lt.name from location l join sales_person as lt on l.location_to = lt.id
UNION ALL
select lf.name from location l join sales_person as lf on l.location_from = lf.id

Upvotes: 0

M Khalid Junaid
M Khalid Junaid

Reputation: 64496

Join sales_person table twice with location to get names for location_to and location_from

select t.name,f.name
from location l
join sales_person t on l.location_to = t.id
join sales_person f on l.location_from = f.id

I assume you have name column in your sales_person table

Upvotes: 2

Related Questions