我的“项目”表(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,我不确定这是否是问题的一部分。
最佳答案
您想使用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;
我还引入了表别名以使查询更易于阅读。
关于SQL 内部联接不返回具有空值的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21668266/