我有以下查询......
SELECT t1.ProductID, t2.Name as [Product Type], t3.Name as [Product Category],
t4.Name as [Product Provider]
From tblProducts t1
Inner Join tblReferences t2 on t1.ProductType = t2.ID
Inner Join tblReferences t3 on t1.ProductCategory = t3.ID
Inner Join tblReferences t4 on t1.ProductProvider = t4.ID
我知道这不是最漂亮的查询,但它完成了这项工作,并且很有可能在最终确定之后不会被编辑。现在,我正在尝试与另一个表进行内部联接以及问题出现的地方......
所以我试图从另一个表格(tblProductSeller)提取数据,但是我需要它显示为[产品提供商]
所以要添加上一个SELECT语句......
SELECT t1.ProductID, t2.Name as [Product Type], t3.Name as [Product Category],
t4.Name as [Product Provider],
t6.SellerName as [Product Provider] <---new line -
然而,这会将其显示为新列,我试图将其显示在与
相同的列中t4.Name as [Product Provider]
我尝试的其余查询是
Inner Join tblReferences t2 on t1.ProductType = t2.ID
Inner Join tblReferences t3 on t1.ProductCategory = t3.ID
Inner Join tblReferences t4 on t1.ProductProvider = t4.ID
Inner Join tblProductSeller t6 on t1.ProductProvider = t6.ID
这样的事情是否可能 - 我是否必须做一个UNION?
编辑。为了保持简短,除了我遇到问题之外,我将放弃大部分领域。 TblProducts
ProductID ProviderID
17 16
18 20
19 24
tblReferences
ID Name
16 Microsoft
20 ADP
tblProductSeller
ID ProductProvider
24 Apple
TblReferences有一些标准卖家的名字,但是,我需要能够引用tblProductSeller,因为很多提供者都会被添加到那里。基本上,这是他们被添加的地方。我的所有数据都存储在tblProducts中。
我的目标是能够填充DataGridView,但是,没有任何ID,而是能够引用tblReferences和tblProductSeller。
所以我的最终结果看起来像
ProductID Contact Provider 16 Microsoft 20 ADP 24 Apple
答案 0 :(得分:2)
根据需要使用哪些表的用例,需要在下面调整语句,但只是为了让你的车轮转动......这是一个例子。
SELECT t1.ProductID,
t2.Name as [Product Type],
t3.Name as [Product Category],
t4.Name as [Product Provider]
From tblProducts t1
Inner Join tblReferences t2
on t1.ProductType = t2.ID
Inner Join tblReferences t3
on t1.ProductCategory = t3.ID
Inner Join tblReferences t4
on t1.ProductProvider = t4.ID
UNION
Select t1.ProductID,
t2.Name as [Product Type],
t3.Name as [Product Category],
t6.Name as [Product Provider]
From tblProducts t1
Inner Join tblReferences t2
on t1.ProductType = t2.ID
Inner Join tblReferences t3
on t1.ProductCategory = t3.ID
Inner Join tblProductSeller t6
on t1.ProductProvider = t6.ID
答案 1 :(得分:1)
这是另一种解决方案,如ebyrob所述:
SELECT t1.ProductID,
t2.Name as [Product Type],
t3.Name as [Product Category],
IsNull(t4.Name, t6.Name) as [Product Provider]
From tblProducts t1
Inner Join tblReferences t2 on t1.ProductType = t2.ID
Inner Join tblReferences t3 on t1.ProductCategory = t3.ID
LEFT Join tblReferences t4 on t1.ProductProvider = t4.ID
LEFT Join tblProductSeller t6 on t1.ProductProvider = t6.ID;
这样做会显示来自Name
的{{1}}(如果有的话),否则会显示tblReferences
中的Name
。您可以根据您的要求重新排序。您可能还希望添加谓词
tblProductSeller
这样可以避免在WHERE t4.ID IS NOT NULL OR t6.ID IS NOT NULL
和tblReferences
匹配的情况下返回多行。