2016-09-26 56 views
0

表結構:如何編寫查詢來獲取主鍵的名稱

Location 
-------------- 
location_id name 
1   Location1 
2   Location2 
3   Location3 

Tour_available 
-------------- 
tour_available_id  from_location to_location 
1       2    3 
2       1    2 
3       2    1 

在上面的表格出發地點和TO_LOCATION的foreign_keys(這是在位置表的主鍵)

我想作爲輸出:

Expected output 
-------------- 
from_location to_location 
Location2   Location3 
Location1   Location2 
Location2   Location1 
+0

加入位置兩次。 – jarlh

回答

1
select FL.name as frm_location, TL.name as t_location 
    from Tour_available as TA INNER JOIN Location as FL ON (FL.location_id = TA.from_location) 
    INNER JOIN Location as TL ON (TL.location_id = TA.to_location); 
0
select 
l1.name as "from_location", 
l2.name as "to_location" 
from Tour_available ta 
join Location l1 on l1.location_id = ta.from_location 
join Location l2 on l2.location_id = ta.to_location 
1

你會ñ eed a join。這個想法是採取tour_available表,然後對from_location上的每個項目使用連接查詢location表。在to_location的相同查詢中重複該操作。這是一個n:m關係

在您的情況,這將是:

SELECT 
    f.name as from_location, -- JUST RENAME OUR COLUMNS TO NICER NAMES 
    t.name as to_location 
FROM 
    tour_available ta, 
    location f,    -- select the table for our "from_location" 
          -- without specifying anything this will 
          -- be treated as a an INNER JOIN. Every location 
          -- in tour_available must match an entry in location. 
    location t    -- select the table for our "to_location" 
WHERE 
    ta.from_location == f.location_id -- from_location selects entry in f 
AND ta.to_location == t.location_id -- to_location selects entry in t 
0
select A.name as from_location,C.name as to_location 
From Location A inner join [dbo].[Tour_available] B 
On A.location_id=B.from_location 
Inner Join 
Location C 
On C.location_id=B.to_location 
相關問題