Hello Stack Overflow社区!我希望有人可以帮助传递一些建议,如果这个查询看起来没问题,是否有任何改进,以及我如何确定行是客户还是供应商。我已经在下面发布了我的代码,提前感谢您的帮助!
Northwind Traders的代表将在德国。管理层希望她在那里访问所有德国供应商和客户。提供德国所有供应商和客户的列表,包括联系人和地址。在报告中指定所列公司是客户还是供应商。
select *
from
Suppliers s
inner join Products p
on s.SupplierID = p.SupplierID
inner join OrderDetails od
on p.ProductID = od.ProductID
inner join Orders o
on od.OrderID = o.OrderID
inner join Customers c
on o.CustomerID = c.CustomerID
where
(s.Country = 'Germany')
and (c.Country = 'Germany')
答案 0 :(得分:0)
您应该单独获取供应商和客户详细信息,并使用UNION ALL
进行合并。事实是,您需要在两个查询中使用相同的列别名,并将新列TYPE
与 SUPPLIER 或 CUSTOMER 相应地引入,如下所示结构,
SELECT SUPPLIERS.NAME AS NAME
..
..
, 'SUPPLIER' AS TYPE
FROM SUPPLIERS
WHERE COUNTRY = 'Germany'
UNION ALL
SELECT CUSTOMERS.NAME AS NAME
..
..
, 'CUSTOMER' AS TYPE
FROM CUSTOMERS
WHERE COUNTRY = 'Germany'
答案 1 :(得分:0)
要仅解决一个Select而不使用SQL进行任何其他操作,您可以使用UNION获取供应商和客户的列:
select 'Supplier' partnerType, s.name, s.contact, s.address
from Suppliers s inner join Products p on s.SupplierID = p.SupplierID
inner join OrderDetails od on p.ProductID = od.ProductID
inner join Orders o on od.OrderID = o.OrderID
where
(s.Country = 'Germany')
Union
Select 'Customer' partnerType, c.name, c.contact, c.address
from Suppliers s inner join Products p on s.SupplierID = p.SupplierID
inner join OrderDetails od on p.ProductID = od.ProductID
inner join Orders o on od.OrderID = o.OrderID
inner join Customers c on o.CustomerID = c.CustomerID
where
(c.Country = 'Germany')
要确定是供应商还是客户,请仅使用列partnerType。
答案 2 :(得分:0)
尝试 -
SELECT CustomerID AS ID,
Customers.Contact AS Contact,
Customers.Address AS Address,
"Customer" AS Type
FROM Customers
WHERE Customers.Country = "Germany"
UNION
SELECT SupplierID,
Suppliers.Contact,
Suppliers.Address,
"Supplier"
FROM Suppliers
WHERE Suppliers.Country = "Germany";
我不确定联系人或地址是一个字段还是多个字段。随意调整以适应桌子的结构。
我建议研究JOIN
和UNION
之间的差异。 UNION
在此处有效,因为两个表中的详细信息具有相同的格式。