如何编写查询以获取主键的名称

时间:2016-09-26 10:28:42

标签: mysql sql

表格结构:

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

在上面的表中,from_location和to_location是foreign_keys(这是Location表中的主键)

我希望输出为:

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

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

您需要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

答案 2 :(得分: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 

答案 3 :(得分: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