好像問題仍然得到一些關注,並努力在這裏提供一些解釋的一些技巧。
如果您只是想要從1到1表中的任何細節的合同,你可以做類似於你所描述的。關鍵是不在列列表中包含Invoices表中的任何列。
SELECT
DISTINCT Contract, Department, ProductId .....(nothing from Invoices Table!!!)
FROM
Contracts c
INNER JOIN Departments D
ON c.departmentId = d.Department
INNER JOIN Product p
ON c.ProductId = p.ProductId
INNER JOIN Invoices i
ON c.contnoC = i.contnoI
也許有點清潔劑將在使用或EXISTS像這樣:
SELECT
Contract, Department, ProductId .....(nothing from Invoices Table!!!)
FROM
Contracts c
INNER JOIN Departments D
ON c.departmentId = d.Department
INNER JOIN Product p
ON c.ProductId = p.ProductId
WHERE
EXISTS (SELECT 1 FROM Invoices i WHERE i.contnoI = c.contnoC)
SELECT
Contract, Department, ProductId .....(nothing from Invoices Table!!!)
FROM
Contracts c
INNER JOIN Departments D
ON c.departmentId = d.Department
INNER JOIN Product p
ON c.ProductId = p.ProductId
WHERE
contnoC IN (SELECT contnoI FROM Invoices)
不要在使用,如果SELECT ...
列表可以返回NULL
!
如果你真的希望所有的合同,只是知道,如果合同已開發票,你可以用聚集和case表達式:
SELECT
Contract, Department, ProductId, CASE WHEN COUNT(i.contnoI) = 0 THEN 0 ELSE 1 END as Invoiced
FROM
Contracts c
INNER JOIN Departments D
ON c.departmentId = d.Department
INNER JOIN Product p
ON c.ProductId = p.ProductId
LEFT JOIN Invoices i
ON c.contnoC = i.contnoI
GROUP BY
Contract, Department, ProductId
然後,如果你真的想返回有關特定發票的細節,你可以使用類似於cybercentic87的技術,如果您的RDBMS支持,或者您可以根據您的系統使用TOP
或LIMIT
的計算列。
SELECT
Contract, Department, ProductId, (SELECT TOP 1 InvoiceNo FROM invoices i WHERE c.contnoC = i.contnoI ORDER BY CreateDate DESC) as LastestInvoiceNo
FROM
Contracts c
INNER JOIN Departments D
ON c.departmentId = d.Department
INNER JOIN Product p
ON c.ProductId = p.ProductId
GROUP BY
Contract, Department, ProductId
你好,告訴我們你嘗試過什麼,請 –
如果你內加入像其他表的發票,但不把從發票表中的任何列到列的列表,並使用DISTINCT你還是應該讓你的1對1其他表格的結果。除此之外,您可以使用IN或EXISTS代替where子句並在那裏引用您的發票表。這個問題應該給你很多方法來解決這個問題。 http://stackoverflow.com/questions/173041/not-in-vs-not-exists – Matt
它會更好,如果你顯示你的整個查詢和你的表結構... – barudo