使用连接的正确方法?

时间:2014-05-13 13:54:38

标签: mysql sql

我不确定如何正确使用联接来获取我正在寻找的数据。我想为每列显示一个lookup_name。

表1

+----------+----------+----------+
|Small City| Med City | Big City |
+----------+----------+----------+
|    22    |    44    |    23    |
+----------+----------+----------+
|    29    |    35    |    88    |
+----------+----------+----------+
|    29    |    26    |    24    |
+----------+----------+----------+

表2

+----------+----------+
|    ID    |  Name    |
+----------+----------+
|    22    |   Paris  |
+----------+----------+
|    23    | Wichita  |
+----------+----------+
|    24    |  Dallas  |
+----------+----------+
|    26    |   Omaha  |
+----------+----------+
|    29    |   Barn   |
+----------+----------+
|    35    | Houston  |
+----------+----------+
|    44    |  Austin  |
+----------+----------+
|    88    |   Miami  |
+----------+----------+

我想从表1中选择,但在每行中显示查找值而不是id。

我甚至不知道加入是否是正确的方法。

4 个答案:

答案 0 :(得分:2)

select
t1.Name as `Small City Name`,
t2.Name as `Med City Name`,
t3.Name as `Big City Name`
from table1 t
inner join table2 t1 on t1.ID = t.`Small City`
inner join table2 t2 on t2.ID = t.`Med City`
inner join table2 t3 on t3.ID = t.`Big City`

答案 1 :(得分:1)

试试这个(诀窍是使用table2 三次):

select sc.Name,
       mc.Name,
       bc.Name
  from table1 t,
       table2 sc,
       table2 mc,
       table2 bc
 where t.SmallCity = sc.ID and
       t.MedCity = mc.ID and
       t.BigCity = bc.ID

或使用加入语法

select sc.Name,
       mc.Name,
       bc.Name
  from table1 t 
         join table2 sc on (t.SmallCity = sc.ID),
         join table2 mc on (t.MedCity = mc.ID),
         join table2 bc on (t.BigCity = bc.ID)

答案 2 :(得分:1)

试试这个

Select 
  t1.[Small City], 
  t2s.Name as SmallCityName, 
  t1.[Med City], 
  t2m.Name as MediumCityName, 
  t1.[Big City],
  t2b.Name as BigCityName
From Table1 t1
INNER JOIN Table2 t2s on t1.[Small City] = t2s.Id
INNER JOIN Table2 t2m on t1.[Med City] = t2m.Id
INNER JOIN Table2 t2b on t1.[Big City] = t2b.Id

答案 3 :(得分:0)

由于您不熟悉连接的概念,我认为以下方式最适合您了解正在发生的事情。您必须为此执行三个连接,因为您希望连接table1的不同列。

select 'Small City', Name from table1 inner join table2 on table1.'Small City' = table2.id

select 'Med City', Name from table1 inner join table2 on table1.'Med City' = table2.id

select 'Big City', Name from table1 inner join table2 on table1.'Big City' = table2.id

其他人建议的解决方案是正确的,但是你很难理解,因为你对连接的概念是全新的。