Mysql 使用联接的正确方法?
我不知道如何正确使用连接来获取我要查找的数据。我想为每列显示一个查找名称 表1Mysql 使用联接的正确方法?,mysql,sql,Mysql,Sql,我不知道如何正确使用连接来获取我要查找的数据。我想为每列显示一个查找名称 表1 +----------+----------+----------+ |Small City| Med City | Big City | +----------+----------+----------+ | 22 | 44 | 23 | +----------+----------+----------+ | 29 | 35 | 88 |
+----------+----------+----------+
|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
我甚至不知道加入是否是正确的方式 由于您对连接的概念还不熟悉,我认为下面的方法最适合您了解正在发生的事情。您必须为此执行三个联接,因为您希望联接表1的不同列
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
其他人建议的解决方案是正确的,但由于您对联接的概念完全陌生,因此您很难理解。试试这个(诀窍是使用表2
三次):
或使用联接语法:
试试这个
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
我不认为这就是汉克斯的意思,这让我走上了正确的道路。
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)
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`
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