2013-03-14 83 views
0

我有一個表USER_TABLE這樣的:如何使用SQL中的另一個表來映射兩列?

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

非常感謝您的幫助。

回答

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

你可以加入到同一個表不止一次:

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 
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 
相關問題