SQL内部联接不返回具有空值的记录

时间:2014-02-10 02:43:08

标签: sql postgresql

我的'items'表(postgreSQL数据库)中有2种不同类型的记录。某些项目与invoiceid相关联,其中包含客户信息。我的项目表中的其他项目没有关联的发票编号。

我正在尝试返回包含发票日期和客户名称的项目列表。没有关联发票或客户的项目也会显示,但这些字段只是空白。问题出在我当前的sql语句中。它仅显示与发票信息关联的项目。

select items.ItemID, items.qty, items.description, customers.firstname,
customers.lastname, invoices.InvoiceDate, items.status 
from items 
inner join Invoices on items.InvoiceID = Invoices.InvoiceID 
inner join customers on Invoices.CustomerID = Customers.CustomerID 
where Items.Status = 'ONTIME' 
ORDER BY InvoiceDate asc

任何想法如何让所有记录显示,或甚至可能?没有数据的字段是NULL,我不确定这是否是问题的一部分。

1 个答案:

答案 0 :(得分:6)

您想使用left outer join代替inner join

select i.ItemID, i.qty, i.description, c.firstname,
       c.lastname, inv.InvoiceDate, i.status 
from items i left outer join
     Invoices inv
     on i.InvoiceID = inv.InvoiceID left outer join
     customers c
     on inv.CustomerID = c.CustomerID 
where i.Status = 'ONTIME' 
order by InvoiceDate asc;

我还引入了表别名,使查询更容易阅读。

相关问题