[英]Oracle SQL Query to order by column value in different table
I'm rather new to sql and am struggling with a statement.我对 sql 比较陌生,并且正在为一个声明而苦苦挣扎。 For simplicity, let's say I have two tables - Table - JourneyOrder, and Table - ItemsToBuy.
为简单起见,假设我有两个表 - 表 - JourneyOrder 和表 - ItemsToBuy。
JourneyOrder has list of cities, index of a particular city in a journey and who is taking the journey. JourneyOrder 包含城市列表、旅程中特定城市的索引以及谁在旅程中。 So:
所以:
City Index Name
London 1 John
Sydney 2 John
Paris 3 John
Berlin 1 Jack
Paris 2 Jack
The other table has a list of items to buy, containing location (as in City), who needs to buy an item, and different characteristics of an item.另一个表有一个要购买的物品列表,包含位置(如在城市中)、需要购买物品的人以及物品的不同特征。
Item Location Weight Price Responsible
Pencil London 1 2 John
Glue London 2 5 John
Car Paris 1000 12000 John
Wallet Paris 3 20 Jack
I want to select all items a particular person needs to buy and order them by location.我想选择特定人需要购买的所有物品并按位置订购。 So if John's first route is London, I want items you can buy in London displayed first.
因此,如果约翰的第一条路线是伦敦,我希望首先显示您可以在伦敦购买的商品。
At the moment, I can use the following:目前,我可以使用以下内容:
SELECT itb.item, itb.location, itb.price
FROM ItemsToBuy itb,
WHERE itb.responsible = 'John'
ORDER BY CASE
WHEN itb.location = 'London' THEN '1'
WHEN itb.location = 'Sydney' THEN '2'
WHEN itb.location = 'Paris' THEN '3'
Now this is obviously terrible, as I need to 'hardcode' the order by part according to the journey each responsible is taking, how can I make it so it matches location of items table to city from journey table and uses the index from the journey table when these match.现在这显然很糟糕,因为我需要根据每个负责人所采取的旅程按部分“硬编码”订单,我如何才能使其将项目表的位置与旅程表中的城市相匹配,并使用旅程中的索引当这些匹配时的表。
I think you just want a join
:我想你只想
join
:
SELECT itb.item, itb.location, itb.price
FROM ItemsToBuy itb JOIN
JourneyOrder jo
ON itb.name = jo.name AND itb.location = jo.city
WHERE itb.responsible = 'John'
ORDER BY jo.index;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.