SQL - 左连接生成重复项

时间:2014-06-09 08:47:31

标签: sql duplicates left-join

我有代码来选择一些应用程序,但LEFT JOIN正在创建重复项。

问题:如何摆脱

生成的重复项
LEFT JOIN
    attachments as att
ON 
    (a.ssn = att.ssn AND att.doc_type = 'id_copy' AND att.source = 'cpt3')

我的工作:

我正在考虑 SELECT DISTINCT GROUP BY 但是,无法确定放置它们的位置。

这是查询:

SELECT
        a.*, c.code, l.who, l.locked_time, att.id AS attnew, 
        ( SELECT 
            COUNT(*) 
          FROM 
            applications as a2 
          WHERE 
            a2.approved = 'Y' 
          AND 
            a2.paid = 'Y' 
          AND 
            a2.paid_back = 'Y' 
          AND 
            a2.ssn = a.ssn 
        ) AS previous_apps
    FROM 
        applications as a
    LEFT JOIN 
        locked_by as l 
    USING(id) 
    LEFT JOIN 
        campaign_codes as c 
    ON 
        c.id = a.campaign
    LEFT JOIN
        attachments as att
    ON 
        (a.ssn = att.ssn AND att.doc_type = 'id_copy' AND att.source = 'cpt3')
    WHERE 
        a.closed='N' 
    AND 
        a.paid = 'N' 
    ORDER BY 
        a.arrived_date 
    DESC

2 个答案:

答案 0 :(得分:0)

如果你想建立一对一的关系以避免重复,att.id对于每个att.ssn是相同的,或者你只需​​要一个(MAX,MIN,.. ANY?){{1 }}。试试这个:

att.id

答案 1 :(得分:0)

使用GROUP BY

避免重复。在你的情况下:

...
    WHERE 
        a.closed='N' 
    AND 
        a.paid = 'N' 
    GROUP BY
        a.id
    ORDER BY 
        a.arrived_date 
    DESC