表中的连接不正常

时间:2016-05-01 07:49:15

标签: sql oracle

我有三张表,它们相互连接在一起。表名是

1) i IOA_INVOICE_LINE
2)  IOA_INVOICE_LINE_NOTES
3) IOA_INV_LINE_NOTE_MAP

附上图像,以图形方式显示您的关系。我试图从iOA_INV_LINE_NOTE_MAP表中获取关于ioa_invoice_line表中每个id列的inv_line_note_id计数。请告知如何获取IOA_INV_LINE_NOTE_MAP表的列inv_line_note_id的计数,其中包含ioa_invoice_line表中id列的上下文。

建议我添加了样本数据:

IOA_INVOICE_LINE  :- 

ID             VERSION
1234            Abc


IOA_INVOICE_LINE_NOTES :-

ID       INLI_ID        NOTES
345      1234           Aqou


INV_LINE_NOTE_MAP :-

ID      INV_LINE_NOTE_ID        ATTACHEMENT
23            345                 rtfffr
24            345                 fhgygg

下面是已经实现的查询,但它没有工作,因为它显示结果为0,应该注意,因为我希望的值应该是2,因为表INV_LINE_NOTE_MAP中有总共2行,对应于列id IOA_INVOICE TABLE的1234请告知如何获取IOA_INV_LINE_NOTE_MAP表的列inv_line_note_id的总计数,并将上下文添加到ioa_invoice_line表中的id列

select ioa_invoice_line.id, count(IOA_INV_LINE_NOTE_MAP.attachment_blob_id) as totalAttachment
from ioa_invoice_line
     left outer join ioa_invoice_line_notes 
              on ioa_invoice_line.id = ioa_invoice_line_notes.inli_id
     left outer join IOA_INV_LINE_NOTE_MAP 
              on ioa_invoice_line_notes.id = IOA_INV_LINE_NOTE_MAP.id
              where  ioa_invoice_line.id =1234 
GROUP BY ioa_invoice_line.id;

还附加了将显示关系的图像 README

1 个答案:

答案 0 :(得分:1)

您的上次加入条件错误,因为它比较了两个主键(都是id):

相反:

select ioa_invoice_line.id, count(IOA_INV_LINE_NOTE_MAP.id) as totalAttachment
from ioa_invoice_line
     left outer join ioa_invoice_line_notes 
              on ioa_invoice_line.id = ioa_invoice_line_notes.inli_id
     left outer join IOA_INV_LINE_NOTE_MAP 
              on ioa_invoice_line_notes.id = IOA_INV_LINE_NOTE_MAP.INV_LINE_NOTE_ID
              where  ioa_invoice_line.id =1234 
GROUP BY ioa_invoice_line.id;

注意INV_LINE_NOTE_ID

如果您有兴趣计算记录,我还建议计算IOA_INV_LINE_NOTE_MAP.id。但是,如果您要排除attachment_blob_idnull的任何记录(可以吗?),请按照您的计算保留计数。

附录:计算条件

如果您只想获取count(IOA_INV_LINE_NOTE_MAP.id) > 0的记录,请将左外连接转换为内连接:

select ioa_invoice_line.id, count(IOA_INV_LINE_NOTE_MAP.id) as totalAttachment
from ioa_invoice_line
     inner join ioa_invoice_line_notes 
              on ioa_invoice_line.id = ioa_invoice_line_notes.inli_id
     inner join IOA_INV_LINE_NOTE_MAP 
              on ioa_invoice_line_notes.id = IOA_INV_LINE_NOTE_MAP.INV_LINE_NOTE_ID
              where  ioa_invoice_line.id =1234 
GROUP BY ioa_invoice_line.id;

但是如果您的条件是计数上的其他内容,那么您可以在分组后使用having子句。它的工作方式类似于where,但在分组发生后执行,您可以引用count等聚合。

例如,如果您只对count(IOA_INV_LINE_NOTE_MAP.id) > 2的情况感兴趣,那么您会写:

select ioa_invoice_line.id, count(IOA_INV_LINE_NOTE_MAP.id) as totalAttachment
from ioa_invoice_line
     inner join ioa_invoice_line_notes 
              on ioa_invoice_line.id = ioa_invoice_line_notes.inli_id
     inner join IOA_INV_LINE_NOTE_MAP 
              on ioa_invoice_line_notes.id = IOA_INV_LINE_NOTE_MAP.INV_LINE_NOTE_ID
              where  ioa_invoice_line.id =1234 
GROUP BY ioa_invoice_line.id
HAVING count(IOA_INV_LINE_NOTE_MAP.id) > 2;