sql left join导致记录不从第二个表中拉出

时间:2017-03-02 19:44:11

标签: sql left-join

我有三个表,trans tarnotes areference_num。所有三个表都有一列i。记录将存在于ta,有时还会i。我想提取ta中的所有记录,如果它在reason中有记录,则显示列i中的数据。

另外,我只想要DISTINCT结果。我目前有以下内容,但它只返回所有三个中都存在的记录。如果a中没有记录,则不会从treason中提取记录,并且SELECT DISTINCT i.BT_ID, i.ST_ID, i.REFERENCE_NUM, i.INVOICE_DATE, i.BALANCE, t.GL_ACCOUNT, a.REASON FROM Invoice i INNER JOIN Trans t ON i.REFERENCE_NUM = t.INVOICE_REFERENCE_NUM LEFT OUTER JOIN ARNOTES a ON t.INVOICE_REFERENCE_NUM = a.INVOICE_NUM WHERE (i.BALANCE > 0) AND (t.GL_ACCOUNT <> '') AND (t.TRANSACTION_TYPE = 'dist') AND (NOT (a.REASON LIKE '%COLLECTIONS%')) 显示空值,则记录根本没有被提取。请帮忙吗?

{{1}}

1 个答案:

答案 0 :(得分:1)

您的not a.REASON like '%COLLECTIONS%'正在将left join转变为内部联接。将其移至ON子句,如下所示:

select distinct i.BT_ID,
    i.ST_ID,
    i.REFERENCE_NUM,
    i.INVOICE_DATE,
    i.BALANCE,
    t.GL_ACCOUNT,
    a.REASON
from Invoice i
inner join Trans t on i.REFERENCE_NUM = t.INVOICE_REFERENCE_NUM
left outer join ARNOTES a on t.INVOICE_REFERENCE_NUM = a.INVOICE_NUM
    and a.REASON not like '%COLLECTIONS%'
where i.BALANCE > 0
    and t.GL_ACCOUNT <> ''
    and t.TRANSACTION_TYPE = 'dist'