2014-02-10 51 views
1

我在'项目'表(postgreSQL数据库)中有2种不同类型的记录。一些项目与invoiceid关联,其中有客户信息关联。我的物品表中的其他物品没有关联的发票号码。SQL内部连接不返回空白值的记录

我试图返回发票日期和客户名称的项目列表。没有发票或客户关联的项目也会显示,但这些字段只是空白。问题出在我目前的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,我不确定这是否是问题的一部分。

回答

5

你想用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; 

我还介绍了表的别名,使查询有点更容易阅读。

+0

作品完美,谢谢! –