UNION ALL是获取此数据的正确方法吗?

时间:2016-03-24 21:17:20

标签: sql postgresql

我有一个Postgres 9.3数据库,其中包含用户和附属机构表。

用户表格列

+----+-------+
|    |       |
+----+-------+
| 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_idreferrer_email替换每个referred_email,然后添加相应的amount。我能做些什么不同的事情?我以为UNION ALL将所有列加在一起。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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