Marius Danciu
Marius Danciu

Reputation: 178

i need to combine two JOIN conditions in a single mysql stament

I have these 2 tables: destinations and prices. destinations have 2 fields: ID and NAME prices have 4 fields: ID_FROM(ID from destinations), ID_TO(ID from destinations), PERSONS, PRICE

I need to make a SQL statement were to change ID_FROM with correspondent NAME and the same for ID_to.

using JOIN in a SQL statement I can only do for one at a time but I need to combine somehow and get both NAMES in the same statement

this works separately:

SELECT     b.name
FROM       dm_prices a
INNER JOIN dm_destinations b
ON         a.from_id = b.id
SELECT     b.name
FROM       dm_prices a
INNER JOIN dm_destinations b
ON         a.to_id = b.id

but I need to combine both in a single query

Upvotes: 0

Views: 32

Answers (1)

forpas
forpas

Reputation: 164064

Join twice the table destinations to dm_prices:

select
  df.name name_from,
  dt.name name_to
from dm_prices p
inner join dm_destinations df on df.id = p.id_from
inner join dm_destinations dt on dt.id = p.id_to

If there is a case of either of the columns id_from or id_to to be null then instead of inner joins use left joins.

Upvotes: 1

Related Questions