Reputation: 5069
I have a table structure where there are CARS
going between BUILDINGS
that are built on PLOTS
:
CARS
CAR_ID | ORIGIN | DESTINATION
----------------------------------
1 | A | C
2 | B | A
3 | A | B
BUILDINGS
BUILD_ID | PLOT
------------------
A | 2
B | 1
C | 3
PLOTS
PLOT_ID | COORD
------------------------
1 | "39.9,-75.5"
2 | "38.3,-74.7"
3 | "37.8,-76.1"
I'm trying to build a query that would show for each CAR
, the PLOT
coordinates of the origin and destination BUILDING
s, like this:
CAR_ID | ORIGIN_COORD | DEST_COORD
-------------------------------------------
1 | "38.3,-74.7" | "37.8,-76.1"
2 | "39.9,-75.5" | "38.3,-74.7"
3 | "39.9,-75.5" | "39.9,-75.5"
This is what I tried but I don't think I'm approaching this right.
SELECT * FROM
(SELECT BUILD_ID, PLOT, COORD FROM BUILDINGS
INNER JOIN PLOTS ON PLOT = PLOT_ID) X
RIGHT JOIN CARS C
ON C.ORIGIN = X.BUILD_ID
Could someone please help me understand how to lookup/join for multiple columns (ORIGIN
and DEST
)?
Upvotes: 1
Views: 55
Reputation: 4743
I know the answers are already here. I add mine here.
select c.car_id,
p1.coord as OriginCoord,
p2.coord as DestinationCoord
from cars as c
left outer join buildings as b1
on c.origin = b1.build_id
left outer join buildings as b2
on c.destination = b2.build_id
left outer join plots as p1
on b1.plot = p1.plot_id
left outer join plots as p2
on b2.plot = p2.plot_id
order by c.car_id
Upvotes: 0
Reputation: 132
I created something like this:
SELECT A.CAR_ID, B2.COORD AS ORIGIN, C2.COORD AS DESTINATION
FROM CARS AS A
LEFT JOIN BUILDINGS AS B
ON A.ORIGIN = B.BUILD_ID
LEFT JOIN PLOTS AS B2
ON B.PLOT = B2.PLOT_ID
LEFT JOIN BUILDINGS AS C
ON A.DESTINATION = C.BUILD_ID
LEFT JOIN PLOTS AS C2
ON C.PLOT = C2.PLOT_ID
Upvotes: 1
Reputation: 2960
Try
SELECT C.car_id, po.coord as origin_coord, pd.cooord as dest_coord
FROM Cars as C
JOIN Buildings as o
on c.origin = o.build_id
JOIN Buildings as d
on c.destination = d.build_id
JOIN Plots as po
on po.plot_id = o.plot
JOIN Plots as pd
on pd.plot_id = d.plot
ORDER BY C.car_id
Upvotes: 1
Reputation: 5103
below is my first thought:
select c.car_id,p1.coord as origin_coord, p2.coord as dest_coord
from cars as c
join buildings as b1 on b1.build_id=c.origin
join buildings as b2 on b2.build_id=c.destination
join plots as p1 on p1.plot_id=b1.plot
join plots as p2 on p2.plot_id=b2.plot
Upvotes: 3