QUOTES TABLE
-----------------
QUOTE_ID_PK PICKUP_FROM_ID DROPOFF_TO_ID
1 4 3
2 2 3
3 1 1
4 1 2
5 3 2
TOWN TABLE
---------------
TOWN_ID_PK DISTANCE NAME
1 34 South Central
2 43 airport
3 99 bus station
4 66 train station
我有2个表来计算一个简单的距离公式。
我需要在订单表中为ORDER_ID返回2行(带距离值)。
我得到order_id = 2的结果,pickupfromdistance = 43,dropoffto = 99。
我已经尝试过这个网站的一些想法,这就是我所拥有的几乎可以工作,但不会返回第二个距离值。我是否以错误的方式解决了这个问题?我是否为一个简单的问题提出了复杂的解决方案?
SELECT town.town_id_pk AS townID, town.distance AS distance, town.name AS townName, town.location AS location, quotes.pickupfrom_id, quotes.dropoffto_id
FROM town, quotes
WHERE quotes.pickupfrom_id=town.town_id_pk
AND quotes.quote_id_pk = '140419420'
UNION ALL
SELECT town.town_id_pk AS townID, town.distance AS distance, town.name AS townName, town.location AS location, quotes.pickupfrom_id, quotes.dropoffto_id
FROM town, quotes
WHERE quotes.dropoffto_id=town.town_id_pk
AND quotes.quote_id_pk = '140419420'";
E.G。 我在选择:
QUOTE_ID_PK=2, wh
(PICKUP_FROM_ID = 2,DROPOFF_TO_ID = 3)
我所追求的结果将是这样的:
TOWN_ID_PK=2, DISTANCE=43, NAME=AIRPORT
然后下一个ROW将是
TOWN_ID_PK=3, DISTANCE=99, NAME= BUS STATION
一旦我知道哪个距离更远,我就可以继续使用代码来计算每千克的速率等等(我可以自己完成这部分)。
答案 0 :(得分:0)
只是给出一个提示:
SELECT
ORDER_ID,
PICKUP_FROM_TOWN_ID,
(SELECT DISTANCE FROM TOWN where TOWN_ID_PK = quotes.DROPOFF_TO_ID) as DISTANCE,
quotes.DROPOFF_TO_ID
from town, quotes
WHERE quotes.PICKUP_FROM_TOWN_ID=town.TOWN_ID_PK
AND ORDER_ID = '140419420'
这是一个sqlfiddle
<强>编辑:强>
为了得到两行,试试这个:
SELECT
ORDER_ID,
PICKUP_FROM_TOWN_ID,
DISTANCE,
DROPOFF_TO_ID
from town, quotes
WHERE
( quotes.PICKUP_FROM_TOWN_ID=town.TOWN_ID_PK or quotes.DROPOFF_TO_ID=town.TOWN_ID_PK )
AND ORDER_ID = 2
答案 1 :(得分:0)
您是否只是为了争取两个城镇的距离?如果是这样,您可以使用join
执行此操作:
select oq.*, tfrom.distance as distance_from, tto.distance as to_distance
from OrderQuotes oq left outer join
Towns tfrom
on oq.PICKUP_FROM_TOWN_ID = tfrom.town_id_pk left outer join
Towns tto
on oq.PICKUP_TO_TOWN_ID = tto.town_id_pk;