我有一个表user_table,如下所示:
USER_TABLE
user1, user2
123 122
323 323
122 125
我有一个单独的表,用户将用户映射到邮政编码。
user_zip
user zipcode
123 32456
323 12983
121 90878
...
现在我要创建一个这样的表:
user1, user2, user1_zip, user2_zip
我看到我可以通过以下查询获得这样的表格:
select user1, user2, zipcode as user1_zip
from user_table as a inner join user_zip as b
on a.user1 = b.user;
不确定如何映射user2,并再获取一个名为user2_zip的列。
非常感谢你的帮助。
答案 0 :(得分:3)
试试这个
SELECT ut.user1, uz1.zipcode AS zip1, ut.user2, uz2.zipcode AS zip2
FROM user_table AS ut
JOIN user_zip AS uz1 ON ut.user1 = uz1.user
JOIN user_zip AS uz2 ON ut.user2 = uz2.user
答案 1 :(得分:1)
您可以多次加入同一张桌子:
select u.user1, u.user2, z1.zipcode [user1_zip], z2.zipcode [user2_zip]
from user_table u
join user_zip z1 on z1.user=u.user1
join user_zip z2 on z2.user=u.user2
答案 2 :(得分:0)
我会做这样的事情:
with temp as (
select user1 u
from user_table
union
select user2 u
from user_table
)
select u.*, uz.*
from temp
inner join user_zip uz on
temp.u = uz.user