我有三个表(没有创建数据库)。它们基本相同,但数据略有不同,它们有Company_Id和Category_Id。我还想将类别名称链接到此表,因此我必须加入类别。 在加入之前,这工作
Select Distinct CompanyId, Category_ID From Product1 where Product1.CompanyId = 10
union
Select Distinct Distinct CompanyId, Category_ID From Product2 where Product2.CompanyId = 10
union
Select Distinct Distinct CompanyId, Category_ID From Product3 where Product3.CompanyId = 10
根据产品ID,我得到了一份产品和类别的清单。
我现在需要在Category表中添加类别名称。我试过了:
Select Distinct CompanyId, Category_ID From Product1 where Product1.CompanyId = 10
inner join Category on Category.Id=Product1.Category_ID
union
Select Distinct Distinct CompanyId, Category_ID From Product2 where Product2.CompanyId = 10
inner join Category on Category.Id=Product2.Category_ID
union
Select Distinct Distinct CompanyId, Category_ID From Product3 where Product3.CompanyId = 10
inner join Category on Category.Id=Product3.Category_ID
但是返回 无法绑定多部分标识符“Company.CATEGORY_ID”。
是否只显示包含所有3个表中类别名称的不同项?
(因此,如果product1和product2都有一个Company_ID = 10的产品,并且有两个类别,它只会显示两次)
答案 0 :(得分:2)
where
位于from
子句之后。 join
关键字是from
的一部分,因此需要先于where
:
Select CompanyId, Category_ID
From Product1 inner join
Category
on Category.Id = Product1.Category_ID
where Product1.CompanyId = 10
union
Select CompanyId, Category_ID From Product2
From Product2 inner join
Category
on Category.Id = Product1.Category_ID
where Product2.CompanyId = 10
union
Select CompanyId, Category_ID From Product3
From Product3 inner join
Category
on Category.Id = Product3.Category_ID
where Product1.CompanyId = 10;
此外,distinct distinct
可能会返回错误。您不需要distinct
关键字,因为您使用的是union
而不是union all
。
答案 1 :(得分:1)
Select distinct CompanyId, Category_ID From Product1
inner join Category on Category.Id=Product1.Category_ID where Product1.CompanyId = 10
union
Select distinct CompanyId, Category_ID From Product2
inner join Category on Category.Id=Product2.Category_ID where Product2.CompanyId = 10
union
Select distinct CompanyId, Category_ID From Product3
inner join Category on Category.Id=Product3.Category_ID where Product3.CompanyId = 10
这未经过测试,但如果没有拼写错误,它应该可以解决您的问题。
答案 2 :(得分:0)
试试这个。我认为首先union
加入Category
表后会更具可读性和可维护性:
with cte as (
select distinct CompanyId, Category_ID from Product1 where Product1.CompanyId = 10
union
select distinct CompanyId, Category_ID from Product2 where Product2.CompanyId = 10
union
select distinct CompanyId, Category_ID from Product3 where Product3.CompanyId = 10
)
select
P.CompanyId, P.Category_ID, c.Category_Name
from cte as P
inner join Category as c on c.Id = P.Category_ID
或者,如果您不喜欢common table expressions,请使用子查询:
select
P.CompanyId, P.Category_ID, c.Category_Name
from (
select distinct CompanyId, Category_ID from Product1 where Product1.CompanyId = 10
union
select distinct CompanyId, Category_ID from Product2 where Product2.CompanyId = 10
union
select distinct CompanyId, Category_ID from Product3 where Product3.CompanyId = 10
)as P
inner join Category as c on c.Id = P.Category_ID