我的“项目”表(postgreSQL数据库)中有2种不同类型的记录。一些项目与发票编号相关联,而发票编号与客户信息相关联。我的项目表中的其他项目没有关联的发票编号。
我正在尝试返回带有发票日期和客户名称的项目列表。没有发票或客户的项目也将显示,但这些字段将为空白。问题出在我当前的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,我不确定这是否是问题的一部分。
您要使用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;
我还介绍了表别名,以使查询更易于阅读。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句