ON
您只需将条件放在WHERE
子查询的子句中,而不是使用子句。
SELECT InvoiceNumber, InvoiceDate,
(SELECT InvoiceLineItemAmount
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
如果您的子查询返回多个值,那么您有几个选择。
你可以抓住TOP 1
SELECT InvoiceNumber, InvoiceDate,
(SELECT TOP 1 InvoiceLineItemAmount
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
您可以使用聚合函数
SELECT InvoiceNumber, InvoiceDate,
(SELECT MAX(InvoiceLineItemAmount)
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
或者您可以使用 XML 连接结果
SELECT InvoiceNumber, InvoiceDate,
STUFF((
SELECT ', ' + LTRIM(InvoiceLineItemAmount)
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID
FOR XML PATH('')),
1, 2, '') AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
或者,对于@MartinSmith,您可以反转关系并改为挂起 InvoiceLineItems。但是,在不知道您的架构约束的情况下,您可能会遇到同样的returns more than one value
问题。
SELECT (SELECT InvoiceNumber
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceNumber,
(SELECT InvoiceDate
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceDate
InvoiceLineItemAmount
FROM InvoiceLineItems
WHERE VendorID = 122
ORDER BY InvoiceDate
最后,这一切都取决于您的要求。