我正在努力让这个查询起作用。我有三个表,我想进行查询以获得红色区域。 每个圆圈都是一个结构不同的表格。我已经管理了很多内部联接的组合,但我特别想要得到所有的红色区域。
付款:idPayment,idInvoice,金额,日期。
B发票:idInvoice,金额日期。
C PromissoryNotes:IdNote,idInvoice,amount,date。
到目前为止......
SELECT B.idInvoice,A.idPayment,C.idNote FROM(发票b INNER JOIN付款a a a.idInvoice = b.idInvoice)LEFT OUTER JOIN PromissoryNotes c ON c.idInvoice = b.idInvoice ORDER BY idInvoice。< / p>
DOESNT QUITE WORK
有什么建议吗?
答案 0 :(得分:3)
你非常接近 - 另一个OUTER JOIN
和一些WHERE
标准可以解决问题:
SELECT B.idInvoice, A.idPayment, C.idNote
FROM Invoice b
LEFT JOIN payments a ON a.idInvoice=b.idInvoice
LEFT JOIN PromissoryNotes c ON c.idInvoice=b.idInvoice
WHERE a.idInvoice IS NOT NULL
OR c.idInvoice IS NOT NULL
ORDER BY B.idInvoice
这基本上说的是给我表B中的所有结果,其中表a或表c中有匹配。
答案 1 :(得分:1)
你可以这两种方式:
1)创建一个集合A,它是B和A的内部联接,创建一个集合C,它是B和C的内部集合,然后是集合A和C.
2)创建一个内部连接A和B的子查询,然后完全外部连接到内部连接C和B的子查询。
1)的例子
SELECT b.idInvoice FROM Invoice B
JOIN Payments A on A.IdInvoice = B.IdInvoice
UNION
SELECT b.idInvoice FROM Invoice B
JOIN PromissoryNotes C on c.idInvoice = B.id Invoice
2)的例子
SELECT idInvoice FROM
(
SELECT b.idInvoice FROM Invoice B
JOIN Payments A on A.IdInvoice = B.IdInvoice
) B FULL OUTER JOIN
(
SELECT b.idInvoice FROM Invoice B
JOIN Payments A on A.IdInvoice = B.IdInvoice
) C on b.idInvoice = C.idInvoice
答案 2 :(得分:0)
尝试
SELECT B.idInvoice, A.idPayment, C.idNote FROM Invoice B INNER JOIN payments A ON A.idInVoice = B.idInvoice INNER JOIN PromissoryNotes C ON C.idInvoice = B.idInvoice ORDER BY idInvoice
INNER JOIN表示您获得两个表的交集。所以这就是你想要的。
答案 3 :(得分:0)
这可以解决这个问题吗?
SELECT
ZZ.idInvoice,
ZZ.idPayment,
YY.idInvoice,
YY.idNote
FROM
(SELECT idInvoice, idPayment
FROM Invoice b
INNER JOIN payments a ON a.idInvoice=b.idInvoice) AS ZZ
FULL OUTER JOIN
(SELECT idInvoice, idNote
FROM PromissoryNotes c
INNER JOIN payments a ON a.idInvoice=c.idInvoice) AS YY ON ZZ.idInvoice = YY.idInvoice
答案 4 :(得分:0)
SELECT p.idInvoice, p.idPayment, idNote
FROM Payments p JOIN Invoice i ON p.adInvoice-i.adInvoice RIGHT OUTER JOIN PromissoryNotes
UNION
SELECT i.idInvoice, idPayment, idNote
FROM Invoice i JOIN PromissoryNotes pn ON i.idInvoice=pn.idInvoice RIGHT OUTER JOIN Payments
您需要包含外部联接,因为要联合的结果表必须具有相同的架构。我相信这些是查询中需要的字段。