postgreSQL中的内部联接获取重复行

时间:2016-01-01 06:55:06

标签: sql database postgresql

我有2个SQL查询。

查询1

traitCollectionDidChange:

查询2

select file_number_fk,sent_date as submitted_date from fl_file_movement 
where sent_by_post_fk='735' 
and file_number_fk='98223'

每个查询返回一个包含7行的表 当我尝试加入他们时我得到49行

select file_number_fk,received_date as received_date from fl_file_movement 
where recipient_post_fk='735' 
and file_number_fk='98223'

我想要一个包含7行的连接表。怎么做

1 个答案:

答案 0 :(得分:0)

我认为您的JOIN条件不够具体,因为您的查询在两个字段上都相同而且JOIN只在其中一个字段上相等,从而将结果相乘:

select distinct  a.file_number_fk, a.received_date, b.submitted_date 
from (select file_number_fk, received_date as received_date 
        from fl_file_movement 
        where recipient_post_fk='735' and file_number_fk='98223') a 
LEFT JOIN (
        select file_number_fk,sent_date as submitted_date 
        from fl_file_movement 
        where sent_by_post_fk='735' 
        and file_number_fk='98223') b 
    ON a.file_number_fk=b.file_number_fk AND a.recipient_post_fk = b.file_number_fk

以上查询基本上是您提供的+额外JOIN条件+提高了可读性。我认为在这种情况下可以删除DISTINCT

此外,您还可以使用SELF JOIN解决此问题。像这样:

SELECT src.file_number_fk, src.received_date, dest.submitted_date
FROM fl_file_movement src
   JOIN fl_file_movement dest ON dest.recipient_post_fk = src.sent_by_post_fk and src.file_number_fk = dest.file_number_fk 
WHERE dest.recipient_post_fk = '735' AND src.file_number_fk = '98223'