2016-03-24 64 views
0

我有一個Postgres 9.3數據庫與用戶和分支表。UNION ALL是獲取這些數據的正確方法嗎?

用戶表列

+----+-------+ 
| |  | 
+----+-------+ 
| id | email | 
+----+-------+ 

分支機構列

+----+------------------+------------------+--------+ 
| id | referred_user_id | referrer_user_id | amount | 
+----+------------------+------------------+--------+ 

我嘗試以下查詢:

select 
    users.email as referred_email, 
    affiliates.amount 
from affiliates 
    JOIN users ON affiliates.referred_user_id = users.id 

UNION ALL 

select 
    users.email as referrer_email, 
    users.id 
from affiliates 
    JOIN users ON affiliates.referrer_user_id = users.id 

它生成表列:

+----------------+--------+ 
| referred_email | amount | 
+----------------+--------+ 

但我希望有一個一對一的表格,如:

+----------------+----------------+--------+ 
| referrer_email | referred_email | amount | 
+----------------+----------------+--------+ 

在那裏我基本上每個替代與*_user_id一個referrer_emailreferred_email,然後在相應的套結amount。我能做些什麼不同?我以爲UNION ALL加在一起的所有列。

+1

'聯盟(全部)'其序列的'SELECT'子句中的列相匹配。它放棄了你在第二個'SELECT'中給列的名字。 – trincot

回答

1

我猜你正在尋找的東西是這樣的:

select u1.referred_email as email1, u2.referrer_email as email2, a.amount 
from affiliates as a, users as u1, users as u2 
where a.referred_user_id = u1.id 
and a.referrer_user_id = u2.id 
2

我想UNION ALL加入所有列在一起。

不,UNION ALL連接行。如果你想加入列,你需要使用JOIN

這看起來可能是這樣:

select 
    rer.email as referrer_email, 
    red.email as referred_email, 
    affiliates.amount 
from affiliates 
    JOIN users rer ON affiliates.referrer_user_id = rer.id 
    JOIN users red ON affiliates.referred_user_id = red.id 
相關問題