如何在一个中加入一个不同的列,在另一个中加入多个?

时间:2015-05-29 01:39:41

标签: sql join

以下是两个示例表(问题和用户):

╔═════════════╦══════════╗
║ reporter_id ║ agent_id ║
╠═════════════╬══════════╣
║ asdf        ║ jfid     ║
║ asde        ║          ║
║ djij        ║ dije     ║
╚═════════════╩══════════╝
╔══════╦════════════╦═══════════╗
║  id  ║ first_name ║ last_name ║
╠══════╬════════════╬═══════════╣
║ asdf ║ Magnus     ║ Nilsson   ║
║ sdfe ║ Thomas     ║ Keller    ║
║ dije ║ Daniel     ║ Humm      ║
╚══════╩════════════╩═══════════╝

期望的结果:

╔═════════════╦══════════╦══════════════════╦═════════════════╦═════════════════════╦════════════════════╗
║ reporter_id ║ agent_id ║ agent_first_name ║ agent_last_name ║ reporter_first_name ║ reporter_last_name ║
╠═════════════╬══════════╬══════════════════╬═════════════════╬═════════════════════╬════════════════════╣
║ asdf        ║ idfj     ║ john             ║ lee             ║ david               ║ lee                ║
║ aiej        ║          ║ mike             ║ dee             ║                     ║                    ║
║ isao        ║ idje     ║ sarah            ║ lee             ║ sarah               ║ dee                ║
╚═════════════╩══════════╩══════════════════╩═════════════════╩═════════════════════╩════════════════════╝

什么样的联接可以处理这个?对于上下文,这将是Redshift(postgres)。我在想这个......

select
    ??? 
from
    issues join users
        on issues.reporter_id = users.id AND issues.agent_id = users.id

我不清楚select子句,我只是对我的from子句是否正确有信心。

2 个答案:

答案 0 :(得分:1)

您需要两次加入User表。您还希望结果数据与表格数据不匹配。

SELECT I.reporter_id, 
       I.agent_id, 
       U1.first_name AS agent_first_name, 
       U1.last_name  AS agent_last_name, 
       U2.first_name AS reporter_first_name, 
       U2.last_name  AS reporter_last_name 
FROM   issues I
       INNER JOIN users U2 
               ON U2.id = I.reporter_id 
       LEFT JOIN users U1 
              ON U1.id = I.agent_id

答案 1 :(得分:0)

您可以两次加入同一张桌子。只需使用不同的别名,如下所示:

select
    issues.reporter_id
   ,issues.agent_id
   ,a.first_name as agent_first_name
   ,a.last_name as agent_last_name
   ,r.first_name as reporter_first_name
   ,r.last_name as reporter_last_name
from
    issues left join users r
        on issues.reporter_id = r.id 
    left join users a
        on issues.agent_id = a.id

此外,由于您有agent_id的空值(并且可能是reporter_id),您需要使用左连接