Left Joins on top of left joins
I'm not really sure how to accomplish what I'm trying to do. Here's a simplified version:
CREATE TABLE PO (
POID int,
PONumber varchar(20)
)
INSERT INTO PO
(POID, PONumber)
VALUES (1, '2520001')
CREATE TABLE WSR (
WSRID int,
POID int,
WSRNumber varchar(1)
)
INSERT INTO WSR
(WSRID, POID, WSRNumber)
VALUES (1, 1, '1')
INSERT INTO WSR
(WSRID, POID, WSRNumber)
VALUES (2, 1, '2')
CREATE TABLE Invoice(
InvoiceID int,
POID int,
InvoiceNumber varchar(20)
)
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (1, 1, '11111111')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (2, 1, '11111111 C010001')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (3, 1, '11111111 H010001')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (4, 1, '11111111 Q010001')
INSERT INTO Invoice
(InvoiceID, POID, InvoiceNumber)
VALUES (5, 1, '22222222')
CREATE TABLE InvoiceMatch(
POID int,
InvoiceID int,
WSRID int)
INSERT INTO InvoiceMatch
(POID, InvoiceID, WSRID)
VALUES (1, 1, 1)
INSERT INTO InvoiceMatch
(POID, InvoiceID, WSRID)
VALUES (1, 5, 2)
From that da开发者_如何学JAVAta, I want to be able to get this result:
PONumber, WSRNumber, InvoiceNumber
2520001 1 11111111
2520001 NULL 11111111 C010001
2520001 NULL 11111111 H010001
2520001 NULL 11111111 Q010001
2520001 2 22222222
The query I'm currently using is this:
SELECT DISTINCT p.POID, p.PONumber, w.WSRNumber, i.InvoiceNumber
FROM PO p
LEFT OUTER JOIN InvoiceMatch im ON im.POID = p.POID
LEFT OUTER JOIN WSR w ON w.POID = im.POID
LEFT OUTER JOIN Invoice i ON i.POID = im.POID
WHERE p.PONumber = '2520001'
but it's not correct. All of the WSRs are linking to every Invoice. Help?
Try this:
SELECT DISTINCT p.POID
,p.PONumber
,w.WSRNumber
,i.InvoiceNumber
FROM PO p INNER JOIN Invoice i
ON i.POID = p.POID LEFT JOIN InvoiceMatch im
ON i.InvoiceID = im.InvoiceID LEFT OUTER JOIN WSR w
ON im.WSRID = w.WSRID
WHERE p.PONumber = '2520001'
I think that the order of your tables in some of your Left Outer Joins
might be off:
SELECT DISTINCT p.POID, p.PONumber, w.WSRNumber, i.InvoiceNumber
FROM PO p
LEFT OUTER JOIN InvoiceMatch im ON p.POID = im.POID
LEFT OUTER JOIN WSR w ON im.POID = w.POID
LEFT OUTER JOIN Invoice i ON m.POID = i.POID
WHERE p.PONumber = '2520001'
Or switch the joins in the previous query to Right Outer Joins
instead of Left.
精彩评论