我有两张桌子:
Table1 (id, name, var1, var2, var3)
Vars (id, name)
以行为例:
表1:
1, John, 3, 6, 7
2, Peter, 1, 4, 3
表二(Vars):
1, Cat
2, Dog
3, Fish
4, Cow
5, Goat
6, Bear
7, Bird
8, Koala
9, Lion
10, Frog
desideres输出是:
1, John, Fish, Bear, Bird
2, Peter, Cat, Cow, Fish
我曾试图使用一些INNER JOINS
,但我认为我做错了,因为我无法获得正确的结果,我怎样才能实现这一目标?感谢
答案 0 :(得分:3)
你需要join
vars
表三次。或者与一行中的变量数一样多的次数。
select t1.id, t1.name, v1.name, v2.name, v3.name
from table1 t1
join vars v1 on v1.id = t1.var1
join vars v2 on v2.id = t1.var2
join vars v3 on v3.id = t1.var3
答案 1 :(得分:2)
使用LEFT JOIN
处理缺失值:
SELECT t1.id, t1.name, v1.name AS name_1, v2.name AS name_2, v3.name AS name_3
FROM Table1 t1
LEFT JOIN Vars v1
ON t1.var1 = v1.id
LEFT JOIN Vars v2
ON t1.var2 = v2.id
LEFT JOIN Vars v3
ON t1.var3 = v3.id