说我有3张桌子:
并非所有报价都有订单,并非所有订单都有报价。
我想要实现的输出是:
Product No | Quotation No | Order No
* * *
* *
* *
目前我可以使用2个查询合并为1来实现此目的。 有什么方法我只能使用1个查询吗?
SELECT Product.ProductNumber, Quotation.QuotationNumber, Order.OrderNumber
FROM Product
JOIN Quotation ON Product.Id = Quotation.ProductId
LEFT JOIN Order ON Product.Id = Order.ProductId AND Quotation.OrderId = Order.Id
UNION
SELECT Product.ProductNumber, NULL, Order.OrderNumber
FROM Product
JOIN Order ON Product.Id = Order.ProductId
LEFT JOIN Quotation ON Product.Id = Quotation.ProductId AND Order.Id = Quotation.OrderId
WHERE Quotation.Id IS NULL
更新:
示例:
Product:
P1
P2
P3
P4
P5
Quotation:
Q1 | P1 | O1
Q2 | P2 | O2
Q3 | P3 | NULL
Order:
O1 | P1
O2 | P2
O3 | P3
O4 | P4
O5 | NULL
Output:
P1 | Q1 | O1
P2 | Q2 | O2
P3 | Q3 | NULL
P3 | NULL | O3
P4 | NULL | O4
我的问题是合并到1:
这就是为什么我必须把它分成2个。但我只是想知道它是否可以用1。
答案 0 :(得分:1)
试试这个:
SELECT Product.ProductNumber, Quotation.QuotationNumber, Order.OrderNumber
FROM Product
LEFT JOIN Quotation ON Product.Id = Quotation.ProductId
LEFT JOIN Order ON Product.Id = Order.ProductId
答案 1 :(得分:0)
试试这个:
SELECT p.Id, q.Id quotation_id, o.Id order_id
FROM Product p
LEFT JOIN Orders o ON p.Id = o.ProductId
LEFT JOIN Quotation q ON p.Id = q.ProductId AND q.OrderId IS NOT NULL
WHERE NOT (q.Id IS NULL AND o.Id IS NULL)
UNION
SELECT p.Id, q.Id quotation_id, NULL
FROM Product p
LEFT JOIN Quotation q ON p.Id = q.ProductId AND q.OrderId IS NULL
WHERE q.Id IS NOT NULL;
由于未定义列的名称,请参阅sqlfiddle文件 http://sqlfiddle.com/#!3/cbc1e/13