我有一個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_email
和referred_email
,然後在相應的套結amount
。我能做些什麼不同?我以爲UNION ALL
加在一起的所有列。
'聯盟(全部)'其序列的'SELECT'子句中的列相匹配。它放棄了你在第二個'SELECT'中給列的名字。 – trincot