我不太确定该如何完成我想做的事情。这是一个简化的版本:

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)


从这些数据中,我希望能够得到以下结果:

PONumber, WSRNumber, InvoiceNumber
2520001   1          11111111
2520001   NULL       11111111 C010001
2520001   NULL       11111111 H010001
2520001   NULL       11111111 Q010001
2520001   2          22222222


我当前正在使用的查询是这样的:

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'


但这是不正确的。所有WSR都链接到每个发票。救命?

最佳答案

试试这个:

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'

关于sql - 左联接在左联接之上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4822100/

10-10 12:58