0

我有一个像这样的表 user_table:

用户表

user1, user2
123    122 
323    323
122    125 

我有一个单独的表格,将用户映射到邮政编码。

用户压缩包

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 的列。

非常感谢您的帮助。

4

3 回答 3

3

Try this

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
于 2013-03-14T20:55:38.950 回答
1

You can join to the same table more than once:

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
于 2013-03-14T20:54:22.947 回答
0

I would do something like this:

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
于 2013-03-14T20:55:23.193 回答