与使用SQL Server中的连接获取不同记录相关的问题

时间:2016-11-10 13:53:12

标签: sql-server join

我在tblProject dataTable:

中有以下列
ID,
Title,
Estimator,
ConstructionCoordinator,
ConstructionManager,
EnteredBy,
AssignedTo,
ProjectCoordinator,
SalesLead

上面没有前两列的所有列都是tblUser Datatable的UserId条目,如下所示

UserId,
UserName

我希望得到tblProject的所有记录,其中所有列(没有前两个,即ID和标题)包含UserId of tblUser

我尝试了以下查询,

 select * from Project PRJ
 inner join UserProfile UP on UP.UserId = PRJ.Estimator or UP.UserId = PRJ.ConstructionCoordinator
                    or UP.UserId = PRJ.ConstructionManager or UP.UserId = PRJ.EnteredBy or UP.UserId = PRJ.AssignedTo
                    or UP.UserId = PRJ.ProjectCoordinator or UP.UserId = PRJ.SalesLead

但是我在列ID and Title中获取重复记录如何获取不同的数据?

由于

1 个答案:

答案 0 :(得分:0)

基于集合的思维,其中intersect类似于逻辑ANDunion类似于逻辑OR,这使我想到了这一点:

select UserId from UserProfile
intersect
( select Estimator from Project
  union
  select ConstructionCoordinator from Project
  union
  select ConstructionManager from Project
  union
  select EnteredBy from Project
  union
  select AssignedTo from Project
  union
  select ProjectCoordinator from Project
  union
  select SalesLead from Project );

要根据您的SQL返回所有列,您可以:

select * from Project where UserId in 
( select Estimator from Project
  union
  select ConstructionCoordinator from Project
  union
  select ConstructionManager from Project
  union
  select EnteredBy from Project
  union
  select AssignedTo from Project
  union
  select ProjectCoordinator from Project
  union
  select SalesLead from Project );